Categories
JavaScript Answers

How to get the objectID after saving an object in Mongoose and JavaScript?

Spread the love

To get the objectID after saving an object in Mongoose and JavaScript, we get the saved document from the returned promise.

For instance, we write

const gnr = new Band({
  name: "Band",
  members: ["Axl", "Slash"],
});

const doc = await gnr.save();

to create a new Band.

And then we call save to return a promise with the saved document.

We use await to get the document from the promise.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *