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

Viewed 124230
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?

10 Answers

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

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");
});

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.

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

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

As per Mongoose v5.x documentation:

The save() method returns a promise. If save() succeeds, the promise resolves to the document that was saved.

Using that, something like this will also work:

let id;
    
n.save().then(savedDoc => {
    id = savedDoc.id;
});

using async function

router.post('/create-new-chat', async (req, res) => {
const chat = new Chat({ name : 'chat room' });
try {
    await chat.save();
    console.log(chat._id);
 }catch (e) {
    console.log(e)
 }
});
Related