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

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

提交回复
热议问题