How do I get the objectID after I save an object in Mongoose?

TIMEX picture TIMEX · Jul 28, 2011 · Viewed 92.2k times · Source
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?

Answer

Richard Holland picture Richard Holland · Jul 28, 2011

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.