var n = new Chat(); n.name = "chat room"; n.save(function(){ //console.log(THE OBJECT ID that I just saved); });
I want to console.log the object id of the object I just saved. How do I do that in Mongoose?
The save() method is asynchronous, and according to the docs, it returns undefined if used with callback or a Promise otherwise.
ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
This just worked for me:
var mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/lol', function(err) { if (err) { console.log(err) } }); var ChatSchema = new Schema({ name: String }); mongoose.model('Chat', ChatSchema); var Chat = mongoose.model('Chat'); var n = new Chat(); n.name = "chat room"; n.save(function(err,room) { console.log(room.id); }); $ node test.js 4e3444818cde747f02000001 $
I'm on mongoose 1.7.2 and this works just fine, just ran it again to be sure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With