How to get the object ID after an object is saved in Mongoose?

Sometimes, we want to get the object ID after an object is saved in Mongoose.

In this article, we’ll look at how to get the object ID after an object is saved in Mongoose.

How to get the object ID after an object is saved in Mongoose?

To get the object ID after an object is saved in Mongoose, we can get the value from the callback that’s run after we call save.

For instance, we write

const {
  Schema
} = require('mongoose')

mongoose.connect('mongodb://localhost/lol', (err) => {
  if (err) {
    console.log(err)
  }
});

const ChatSchema = new Schema({
  name: String
});

mongoose.model('Chat', ChatSchema);

const Chat = mongoose.model('Chat');

const n = new Chat();
n.name = "chat room";
n.save((err, room) => {
  console.log(room._id);
});

to create a schema with the Schema constructor.

Next, we register that Chat model with mongoose.model.

Then create a new document with the Chat model.

Finally, we call save with the saved document data set as the value of room.

And we get the object ID of the saved document from room._id.

Conclusion

To get the object ID after an object is saved in Mongoose, we can get the value from the callback that’s run after we call save.