Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document must have an _id before saving mongoose error

I am trying to create a schema.

I keep getting the document does not have an _id error, besides the code below I did try to initialize it explicitly, but nothing works.

var UserSchema = new mongoose.Schema({
     _id: mongoose.Schema.ObjectId,
     username: String,
     password: String
 });

var User = mongoose.model('user', UserSchema);
like image 451
Rishav Pandey Avatar asked Dec 05 '25 13:12

Rishav Pandey


1 Answers

http://mongoosejs.com/docs/guide.html#_id reads:

Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor.

If you explicitly define _id type in the schema, it's your responsibility to set it:

User._id = mongoose.Types.ObjectId('000000000000000000000001');
like image 172
Alex Blex Avatar answered Dec 08 '25 06:12

Alex Blex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!