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

后端 未结 8 1946
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:32

    Mongo sends the complete document as a callbackobject so you can simply get it from there only.

    for example

    n.save(function(err,room){
      var newRoomId = room._id;
      });
    
    0 讨论(0)
  • 2020-12-05 04:34

    you can get objectid in mongoosejs after you new some model.

    i'm using this code work in mongoose 4, you can try it in other version

    var n = new Chat();
    var _id = n._id;
    

    or

    n.save((function (_id) {
      return function () {
        console.log(_id);
        // your save callback code in here
      };
    })(n._id));
    
    0 讨论(0)
提交回复
热议问题