Get the _id of Inserted Document in Mongo Database in Node.js

This article will show how to get the _id of Inserted Document in Mongo Database in Node.js.

In MongoDB, each document is assigned a unique identifier called _id. When inserting a new document into a collection using Node.js, you may want to retrieve the _id of the inserted document for further use.

Using Object Reference (Shorter Way)

The MongoDB driver for Node.js appends the _id field to the original object reference during insertion. You can take advantage of this by accessing the _id property directly inside the callback function.

const objectToInsert = { /* Your document data */ };

collection.insert(objectToInsert, function(err) {
    if (err) return console.error(err);

    // Object inserted successfully.
    const objectId = objectToInsert._id; // Get the _id of the inserted object
    console.log("Inserted object ID:", objectId);
});

Explanation:

  • objectToInsert is the document you want to insert into the MongoDB collection.
  • The collection.insert method is used to insert the document into the collection.
  • Inside the callback function, the _id of the inserted object is directly accessed from the original object reference.

Using Callback Parameter

Another way to obtain the _id is by utilizing the second parameter of the callback function for the collection.insert method. This parameter contains information about the inserted documents, including their _ids.

const objectToInsert = { /* Your document data */ };

collection.insert(objectToInsert, function(err, docsInserted) {
    if (err) return console.error(err);

    // Output the entire inserted document(s) information
    console.log(docsInserted);

    // Access the _id of the first inserted document
    const objectId = docsInserted.ops[0]._id;
    console.log("Inserted object ID:", objectId);
});

Explanation:

  • Similar to Method 1, objectToInsert is the document you want to insert.
  • The callback function now takes two parameters: err and docsInserted, where docsInserted contains information about the inserted document(s).
  • The _id of the first inserted document is accessed using docsInserted.ops[0]._id.

Using insertedId Property

You can directly access the insertedId property on the result object to obtain the _id of the inserted document. This method is demonstrated using promises.

const documentToInsert = { /* Your document data */ };

db.collection("collection-name")
  .insertOne(documentToInsert)
  .then(result => {
    const objectId = result.insertedId;
    console.log("Inserted object ID:", objectId);
  })
  .catch(err => {
    console.error(err);
    // Handle error
  });

Explanation:

  • documentToInsert is the document to be inserted.
  • insertOne is a method provided by the MongoDB driver for Node.js to insert a single document into a collection.
  • The result of the insertion operation is a promise, and the _id is accessed using result.insertedId.

Converting to String

If you prefer the _id as a string, you can convert it using the toString() method.

const result = /* result from insertion operation */;

const objectIdAsString = result.insertedId.toString();
console.log("Inserted object ID as String:", objectIdAsString);

Explanation:

  • Assuming result is the result from the insertion operation.
  • The _id is obtained using result.insertedId.
  • The _id is converted to a string using the toString() method.

Extracting _id from Callback Object

MongoDB sends the complete document as a callback object. You can directly extract the _id from this callback object.

collection.save(function(err, room) {
    if (err) return console.error(err);

    const newRoomId = room._id;
    console.log("Inserted object ID:", newRoomId);
});

Explanation:

  • collection.save is used to save a document into the collection.
  • The callback function receives two parameters: err and room.
  • The _id of the inserted document is accessed directly from the callback object (room).

Using Async Functions

You can use async functions to get the _id field automatically without manipulating the data object explicitly.

async function save() {
  const data = {
    name: "John"
  };

  await db.collection('users').insertOne(data);

  // The data object now contains the _id field
  return data;
}

// Example usage
save().then(result => {
  console.log("Inserted object ID:", result._id);
});

Explanation:

  • save is an asynchronous function that inserts a document into the “users” collection.
  • The _id of the inserted document is automatically part of the returned data object.
  • The function is called using save().then(...), and the _id is accessed from the resolved promise.

Choose the method that best fits your application’s structure and requirements. Each method provides a way to obtain the _id of the inserted document in a slightly different manner.

Leave a Comment

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

Scroll to Top