Mongoose: If you explicitly declare _id: Schema.ObjectId for your model, then the ObjectId will not be available after new or save.

Created on 11 Jan 2013  路  6Comments  路  Source: Automattic/mongoose

If you explicitly declare

_id: Schema.ObjectId

for your model, then the ObjectId will not be available after new or save.

Most helpful comment

ah, the docs were incorrectly hiding the option you need (will be fixed next time they're published).

you must pass the auto option like so:

new Schema({ _id: { type: Schema.ObjectId, auto: true }})

All 6 comments

please post code to reproduce.

Source: http://stackoverflow.com/questions/6074245/node-mongoose-get-last-inserted-id
But here is the code too:

var SerialSchema = new Schema({
     _id        : ObjectId
    ,serial     : String
    ,year       : Number
}, { strict: true
    ,toObject: {
      virtuals: true
    }
    ,toJSON: {
      virtuals: true
    }
});

var serial = new Serial({serial: 'abc', year: 2012});
serial.save(function(err, _serial){
    // no error
    // serial._id or serial.id is not defined
    // _serial._id or _serial.id is not defined too
})

"version": "3.4.0",

ah, the docs were incorrectly hiding the option you need (will be fixed next time they're published).

you must pass the auto option like so:

new Schema({ _id: { type: Schema.ObjectId, auto: true }})

thanks

new Schema({ _id: { type: Schema.ObjectId, auto: true }})
"CHANGE (_id) to (id)"

Was this page helpful?
0 / 5 - 0 ratings

Related issues

simonxca picture simonxca  路  3Comments

ghost picture ghost  路  3Comments

CodeurSauvage picture CodeurSauvage  路  3Comments

weisjohn picture weisjohn  路  3Comments

adamreisnz picture adamreisnz  路  3Comments