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

后端 未结 8 1995
Happy的楠姐
Happy的楠姐 2020-12-05 03:37
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 ob

8条回答
  •  误落风尘
    2020-12-05 04:17

    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.

提交回复
热议问题