I\'ve been struggling so much with this project. I am following a tutorial that is out of date in some areas, for instance their version of Jquery used a totally different f
_id is added automatically by MongoDb.
If you want to keep _id on your data structure be sure to initialize correctly:
var obj = new UserSchema({
"_id": new ObjectID(),
"username": "Bill",
"password" : "...."
});
Its pretty simple:
What you can't do, is to have it in the schema but not initialize it. It will throw the error you are talking about
Try below snippet I wanted to name _id as userId you can do without it as well.
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var UserSchema = new Schema({
username: String,
password: String
});
UserSchema.virtual('userId').get(function(){
return this._id;
});
No need to specify the document _id in your model. The system generates the id automatically if you leave out the _id like so:
var UserSchema = new mongoose.Schema({
username: String,
password: String
});
That being said, if you still want to generate the _id yourself, see the answers above.
You can write your model without _id so it will be autogenerated
or
you can use .init() to initialize the document in your DB.
Like:
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
username: String,
password: String
})
module.exports = mongoose.model('User', UserSchema);
and then
const User = require('../models/user');
router.post('/addUser',function(req,res,next){
User.init() // <- document gets generated
const user = new User({
username: req.body.username,
password: req.body.password
})
user.save().then((data)=>{
console.log('save data: ',data)
// what you want to do after saving like res.render
})
}
In my case, I accidentally had the following at the end of my Schema. Removing that worked:
{ _id: false }