How to Get the id of Inserted Document in MongoDB in NodeJS
Last Updated :
26 Apr, 2024
MongoDB is a popular type of NoSQL database. It stores data in documents that look like JSON. When working with MongoDB using Mongoose, _id is a unique identifier of each document in a collection and it can be used to perform operations on the document, such as updating or deleting it. The insertion method is used to insert a document into a MongoDB collection.
In this article, We will learn about the process of Getting the _id of the inserted document in Mongo database in NodeJS by understanding the various methods along with the examples and so on.
How to get the ID of the Inserted Document?
When working with MongoDB and Mongoose developers often need to perform tasks such as updating documents, Inserting documents, and executing complex queries. The below methods help us to understand How to get the ID of the Inserted Document are as follow:
- Using insertOne() Method with insertedId Property
- Using insertOne() Method with ops Property
Steps to Create Database Connection and Mongoose Schema
Step 1: Install Necessary Dependencies
npm install mongoose express
Step 2: Create the MongoDB connection
Create a dbConnect.js file and paste the below code
const mongoose = require("mongoose");
mongoose
.connect("mongodb://localhost:27017/gfg")
.then(() => {
console.log("Connected to MongoDB database successfully!");
})
.catch((err) => {
console.error("Error connecting to MongoDB:", err);
});
Step 3: Create a Mongoose Schema
Create a model.js file, which includes the Mongo schema [courseSchema] with fields like Title, Fees, Instructor & Date.
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
Title: {
type: String,
},
Fees: {
type: Number,
},
Instructor: {
type: String,
},
date: Date,
});
const Course = mongoose.model("Course", courseSchema);
module.exports = Course;
1. Using insertOne() Method with insertedId Property
In the MongoDB, insertOne() method is used to insert a single document into the collection. It also returns the document that contains inserted document details & inserted Id property.
Syntax:
db.collection.insertOne(document, callback)
- document: The document to be inserted into the collection.
- callback: An optional callback function that is called after the insertion is complete
Example 1: Adding the Java course and getting the Inserted Id
const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");
async function insertData() {
try {
const javaCourse = new Course({
Title: "Java",
Fees: 10000,
Instructor: "Akhil Sir",
date: new Date("2024-03-23"),
});
const savedCourse = await javaCourse.save();
const insertedId = savedCourse._id;
console.log("Inserted document _id:", insertedId);
console.log("Data inserted successfully");
const insertedData = await Course.find({});
console.log("Inserted data:");
console.log(insertedData);
} catch (error) {
console.error("Error inserting data:", error);
} finally {
mongoose.disconnect();
}
}
insertData();
Output:
Server is running on port 3000
MongoDB connected
Inserted document _id: new ObjectId('662894fbef2273c58f5d1592')
Data inserted successfully
Inserted data:
[
{
_id: new ObjectId('662894fbef2273c58f5d1592'),
Title: 'Python',
Fees: 25000,
Instructor: 'Sushant Sir',
date: 2024-03-23T00:00:00.000Z,
__v: 0
}
]
Example 2: Adding the Python course & getting the Inserted Id
const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");
async function insertData() {
try {
const pythonCourse = new Course({
Title: "Python",
Fees: 25000,
Instructor: "Sushant Sir",
date: new Date("2024-03-23"),
});
const savedCourse = await pythonCourse.save();
const insertedId = savedCourse._id;
console.log("Inserted document _id:", insertedId);
console.log("Data inserted successfully");
const insertedData = await Course.find({});
console.log("Inserted data:");
console.log(insertedData);
} catch (error) {
console.error("Error inserting data:", error);
} finally {
mongoose.disconnect();
}
}
insertData();
Output:
Server is running on port 3000
MongoDB connected
Inserted document _id: new ObjectId('662894c857ef020ca85343f0')
Data inserted successfully
Inserted data:
[
{
_id: new ObjectId('662894c857ef020ca85343f0'),
Title: 'Python',
Fees: 25000,
Instructor: 'Sushant Sir',
date: 2024-03-23T00:00:00.000Z,
__v: 0
}
]
2. Using the insertOne() method with the ops property
In the MongoDB, insertOne() returns a result object that contains an ops property, which is an array of documents that were inserted and the ops property contains the full document or documents that were inserted into the collection.
Syntax:
db.collection.insertOne(document, callback)
- document: The document to be inserted into the collection.
- callback: An optional callback function that is called after the insertion is complete
- The ops field is not directly used in above examples. In some cases, the ops field in the result object may contain an array of inserted documents.
Example 1: Adding the Java course and getting the Inserted Id
const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");
async function insertData() {
try {
const courseObject = {
Title: "Java",
Fees: 10000,
Instructor: "Akhil Sir",
date: new Date("2024-03-23"),
};
const result = await Course.collection.insertOne(courseObject);
if (result && result.acknowledged && result.insertedId) {
const insertedId = result.insertedId;
console.log("Inserted document _id:", insertedId);
} else {
throw new Error(
"Failed to insert document or inserted document is empty."
);
}
console.log("Data inserted successfully");
const insertedData = await Course.find({});
console.log("Inserted data:");
console.log(insertedData);
} catch (error) {
console.error("Error inserting data:", error);
} finally {
mongoose.disconnect();
}
}
insertData();
Output:
Server is running on port 3000
MongoDB connected
Inserted document _id: new ObjectId('66289473049ee4bee5048def')
Data inserted successfully
Inserted data:
[
{
_id: new ObjectId('66289473049ee4bee5048def'),
Title: 'Java',
Fees: 10000,
Instructor: 'Akhil Sir',
date: 2024-03-23T00:00:00.000Z
}
]
Example 2: Adding the Python course and getting the Inserted Id
const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");
async function insertData() {
try {
const courseObject = {
Title: "Python",
Fees: 15000,
Instructor: "Nikhil Sir",
date: new Date("2024-03-23"),
};
const result = await Course.collection.insertOne(courseObject);
if (result && result.acknowledged && result.insertedId) {
const insertedId = result.insertedId;
console.log("Inserted document _id:", insertedId);
} else {
throw new Error(
"Failed to insert document or inserted document is empty."
);
}
console.log("Data inserted successfully");
const insertedData = await Course.find({});
console.log("Inserted data:");
console.log(insertedData);
} catch (error) {
console.error("Error inserting data:", error);
} finally {
mongoose.disconnect();
}
}
insertData();
Output:
Server is running on port 3000
MongoDB connected
Inserted document _id: new ObjectId('66289434eec367e5b13ef946')
Data inserted successfully
Inserted data:
[
{
_id: new ObjectId('66289434eec367e5b13ef946'),
Title: 'Python',
Fees: 15000,
Instructor: 'Nikhil Sir',
date: 2024-03-23T00:00:00.000Z
}
]
Conclusion
Overall summary, In the above approaches we are using the insertOne with ops property & insertedId property to insert the document in MongoDb collection. and result from these methods contains information of inserted documents with id. so we can easily access the insertedId property using _id ,and the ops array. The above approachs allows developer to easily obtain the unique identifier(s) assigned by MongoDB to the newly inserted documents, which can be useful for various purposes, such as referencing or updating the documents later on.
Similar Reads
How to Get only the Objecte of Document in MongoDB
In MongoDB, the ability to extract specific objects from documents is an important skill that can significantly enhance our data retrieval capabilities. MongoDB's flexible document model allows for nested structures, where documents can contain arrays or sub-documents. However, retrieving only the d
3 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _i
3 min read
How to find all the document keys of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
1 min read
How to replace one document in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Inst
1 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to Get the Insert ID in SQL?
When working with SQL databases, obtaining the insert ID (the auto-incremented primary key value) after inserting a new record is crucial for managing data relationships and ensuring seamless data referencing. In SQL databases, obtaining the insert ID after adding a new record to a table is a common
4 min read
How to insert single and multiple documents in Mongodb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to Find Documents by ID in MongoDB?
In MongoDB, finding documents by their unique identifier (ID) is a fundamental operation that allows us to retrieve specific records efficiently. Each document in a MongoDB collection has a unique _id field, which serves as the primary key. In this article, we will explore how to find documents by I
3 min read
Filtering MongoDB Documents by ID in Node.js with Express.js
Filtering is a very basic feature that an API must possess to serve data to the client application efficiently. By handling these operations on the server side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In this article,
4 min read