Open In App

How to Insert a Document into a MongoDB Collection using Node.js?

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guide on how to accomplish this using Node.js.

Prerequisites:

The steps to insert documents in MongoDB collection are given below

Steps to Setup the Project

Step 1: Create a nodeJS application by using this command

npm init 
or
npm init -y
  • npm init command asks some setup questions that are important for the project
  • npm init -y command is used to set all the answers of the setup questions as yes.

Step 2: Install the necessary packages/libraries in your project using the following commands.

npm install mongodb

Project Structure:

Project-Structure
Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"mongodb": "^6.6.1"
}

NodeJS and MongoDB Connection

Once the MongoDB is installed we can use MongoDB database with the Nodejs Project.Initially we need to specify the database name ,connection URL and the instance of MongoDBClient.

const { MongoClient } = require('mongodb');
// or as an ecmascript module:
// import { MongoClient } from 'mongodb'

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

const dbName = 'project_name'; // Database Name

async function main() {

await client.connect();
console.log('Connected successfully to server');

const db = client.db(dbName);
const collection = db.collection('collection_name');

//Can Add the CRUD operations
}

main() .then(console.log)
.catch(console.error)
.finally(() => client.close());
  • MongoClient class provided method, to connect MongoDB and Nodejs.
  • client is the instance of MongoDb and Node Js connection.
  • client.connect() is used to connect to MongoDB database ,it awaits until the the connection is established.

Create a Collection in MongoDb using Node Js

In this operation we create a collection inside a database.Intilally we specify the database in which collections is to be created.

//Sepcify Database
const dbName = 'database_name';

const db = client.db(dbName);

//Create Collection
const collection = db.collection('collection_name');
  • client is the instance of the connection which provides the db() method to create a new Database.
  • collection() method is used to set the instance of the collection .

Insert a Single Document

To insert a document into the collection insertOne() method is used.

const insertDoc = await collection.insertOne({
filed1: value1,
field2: value2,
);

//Insert into collection
console.log('Inserted documents =>', insertDoc);

Insert Many Document

To insert a document into the collection insertMany() method is used.

const doc_array = [
{ document1 },
{ document2 },
{ document3 },
];

//Insert into collection
const insertDoc =
await collection.insertMany(doc_array);
console.log('Inserted documents =>', insertDoc);

Handling Insertion Results

In a project we have different tasks which needs to be executed in specific order.In the MongoDB and Node Js project we must ensure that connection is set.While performing insertion of documents , we perform asynchronous insertion so that execution is not interrupted.We use try-catch block to handle errors while setting up connection, inserting document or while performing any other operation. If an error occurs during execution ,catch block handles it or provide the details about the error ,which helps to resolve the error.

try {
const dbName = 'database_name';
await client.connect();
const collection = db.collection('collection_name');

const doc_array = [
{ document1 },
{ document2 },
{ document3 },
];

//Insert into collection
const insertDoc = await collection.insertMany(doc_array);

console.log('Inserted documents =>', insertDoc);
} catch (error) {
console.error('Error:', error);
}
  • Initally connection is established .AS the connection is established insertMany() method or insertOne() method is used to insert the document in the collection.
  • insertDoc stores the result of the insertion which is further logged.

Read Documents from the collection

We can read the documents inside the collection using the find() method.

const doc = await collection.find({}).toArray();
console.log('Found documents =>', doc );

find() method is used to along with empty {} are used to read all the documents in the collection.Which are further converted into the array using the toArray() method.

Closing the Connection

finally{  
client.close()
}
  • Once the promise is resolved or rejected , code in finally block is executed. The close() method is used to close the connection.
  • Connection is closed irrespective of the error .It is generally used to cleanup and release the resource.

Example: Implementation to show Insertion of documents into a MongoDB collection using Node.js

JavaScript
const { MongoClient } = require("mongodb");

async function main() {
    const url = "mongodb://127.0.0.1:27017";
    const dbName = "GeeksforGeeks";
    const studentsData = [
        { rollno: 101, Name: "Raj ", favSub: "Math" },
        { rollno: 102, Name: "Yash", favSub: "Science" },
        { rollno: 103, Name: "Jay", favSub: "History" },
    ];

    let client = null;

    try {
        // Connect to MongoDB
        client = await MongoClient.connect(url);
        console.log("Connected successfully to MongoDB");

        const db = client.db(dbName);
        const collection = db.collection("students");

        // Add students to the database
        await collection.insertMany(studentsData);
        console.log("Three students added successfully");

        // Query all students from the database
        const students = await collection.find().toArray();
        console.log("All students:", students);
    } catch (err) {
        console.error("Error:", err);
    } finally {
        // Close the connection
        if (client) {
            client.close();
            console.log("Connection closed successfully");
        }
    }
}

main();

Output:

Insert-Document-in-MongoDB
Insert Document in MongoDB

Explanation :

In the above example, Initially MongoClient class is imported which is used to connect MongoDB and Nodejs .client is the instance of MongoDb and Node Js connection. which is used to name the database .As database is set ,collection() method sets the instance of the collection .Three documents are inserted in the students collection using insertMany() method .Error during the execution are handled using the try catch block ,finally connection is closed using the close() method

Conclusion

Inserting a document into a MongoDB collection using Node.js involves setting up a MongoDB client, connecting to the database, and using the appropriate methods to perform the insert operation. This guide has covered the basics, but MongoDB's Node.js driver offers many more features for advanced database interactions. For more information, check out the official MongoDB Node.js Driver documentation.


Next Article

Similar Reads