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

后端 未结 8 1945
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:08

    Actually the ID should already be there when instantiating the object

    var n = new Chat();
    console.log(n._id) // => 4e7819d26f29f407b0... -> ID is already allocated
    

    Check this answer here: https://stackoverflow.com/a/7480248/318380

    0 讨论(0)
  • 2020-12-05 04:10

    With save all you just need to do is:

    n.save((err, room) => {
      if (err) return `Error occurred while saving ${err}`;
    
      const { _id } = room;
      console.log(`New room id: ${_id}`);
    
      return room;
    });
    

    Just in case someone is wondering how to get the same result using create:

    const array = [{ type: 'jelly bean' }, { type: 'snickers' }];
    
    Candy.create(array, (err, candies) => {
      if (err) // ...
    
      const [jellybean, snickers] = candies;
      const jellybeadId = jellybean._id;
      const snickersId = snickers._id;
      // ...
    });
    

    Check out the official doc

    0 讨论(0)
  • 2020-12-05 04:10

    Well, I have this:

    TryThisSchema.post("save", function(next) {
        console.log(this._id);
    });
    

    Notice the "post" in the first line. With my version of Mongoose, I have no trouble getting the _id value after the data is saved.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 04:19

    Other answers have mentioned adding a callback, I prefer to use .then()

    n.name = "chat room";
    n.save()
    .then(chatRoom => console.log(chatRoom._id));
    

    example from the docs:.

    var gnr = new Band({
      name: "Guns N' Roses",
      members: ['Axl', 'Slash']
    });
    
    var promise = gnr.save();
    assert.ok(promise instanceof Promise);
    
    promise.then(function (doc) {
      assert.equal(doc.name, "Guns N' Roses");
    });
    
    0 讨论(0)
  • 2020-12-05 04:29

    You can manually generate the _id then you don't have to worry about pulling it back out later.

    var mongoose = require('mongoose');
    var myId = mongoose.Types.ObjectId();
    
    // then set it manually when you create your object
    
    _id: myId
    
    // then use the variable wherever
    
    0 讨论(0)
提交回复
热议问题