MongoDB - Error: document must have an _id before saving

删除回忆录丶 提交于 2019-11-30 17:46:55

Its pretty simple:

  1. If you have declared _id field explicitly in schema, you must initialize it explicitly
  2. If you have not declared it in schema, MongoDB will declare and initialize it.

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;
});

_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" : "...." 
});

Do not specify _id: mongoose.Schema.ObjectId in your model. The system creates the id if you leave out the _id like so:

var UserSchema = new mongoose.Schema({    
    username: String,
    password: String
}); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!