w3resource

Using MongoDB with Node.js: Setup and CRUD Operations Guide


Using MongoDB with Node.js

MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Combining MongoDB with Node.js allows developers to build scalable, real-time applications with ease. This guide provides detailed steps to set up and use MongoDB with Node.js, including installation, CRUD operations, and examples using the official mongodb driver.


Syntax:

To interact with MongoDB in Node.js:

    1. Install the MongoDB driver: npm install mongodb.

    2. Import the driver and connect to a MongoDB database.

    3. Perform CRUD (Create, Read, Update, Delete) operations.


Examples and Code

1. Installation and Setup

Install the MongoDB driver:

npm install mongodb

Set up a MongoDB database on your local machine or use a cloud service like MongoDB Atlas.

2. Connecting to MongoDB

Example Code:

Code:

// Import the MongoDB client
const { MongoClient } = require('mongodb');

// Define the MongoDB connection URI
const uri = 'mongodb://localhost:27017'; // Replace with your database URI

// Create a new MongoClient instance
const client = new MongoClient(uri);

async function connectToDB() {
    try {
        // Connect to the MongoDB server
        await client.connect();

        console.log('Connected to MongoDB');
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    } finally {
        // Close the connection
        await client.close();
    }
}

// Call the function to connect
connectToDB();

Explanation:

  • MongoClient: Creates a client to connect to the database.
  • await client.connect(): Establishes the connection.
  • client.close(): Closes the connection after operations.

3. Performing CRUD Operations

Create: Insert Documents

Code:

async function insertDocuments() {
    const db = client.db('testdb'); // Specify the database
    const collection = db.collection('users'); // Specify the collection

    // Insert multiple documents
    const result = await collection.insertMany([
        { name: 'Alice', age: 25 },
        { name: 'Bob', age: 30 },
    ]);

    console.log(`${result.insertedCount} documents inserted`);
}

Read: Query Documents

Code:

async function findDocuments() {
    const db = client.db('testdb'); // Specify the database
    const collection = db.collection('users'); // Specify the collection

    // Find all documents
    const users = await collection.find({}).toArray();
    console.log('Users:', users);
}

Update: Modify Documents

Code:

async function updateDocuments() {
    const db = client.db('testdb'); // Specify the database
    const collection = db.collection('users'); // Specify the collection

    // Update a document
    const result = await collection.updateOne(
        { name: 'Alice' }, // Filter
        { $set: { age: 26 } } // Update operation
    );

    console.log(`${result.modifiedCount} document(s) updated`);
}

Delete: Remove Documents

Code:

async function deleteDocuments() {
    const db = client.db('testdb'); // Specify the database
    const collection = db.collection('users'); // Specify the collection

    // Delete a document
    const result = await collection.deleteOne({ name: 'Bob' });

    console.log(`${result.deletedCount} document(s) deleted`);
}

4. Running All Operations Together

Code:

async function main() {
    try {
        await client.connect(); // Connect to the database
        console.log('Connected to MongoDB');

        await insertDocuments(); // Perform Create
        await findDocuments();  // Perform Read
        await updateDocuments(); // Perform Update
        await deleteDocuments(); // Perform Delete
    } catch (error) {
        console.error('Error:', error);
    } finally {
        await client.close(); // Close the connection
    }
}

// Call the main function
main();

Best Practices for Using MongoDB with Node.js

    1. Use Environment Variables: Store sensitive information like the connection URI in environment variables.

    2. Enable Connection Pooling: Reuse connections to enhance performance in production environments.

    3. Index Your Data: Use indexes for frequently queried fields to improve performance.

    4. Validate Data: Use schemas and libraries like Mongoose for data validation.

    5. Handle Errors Gracefully: Wrap database calls in try...catch blocks to manage errors effectively.


Common MongoDB Commands

Command Purpose
npm install mongodb Install the MongoDB Node.js driver.
db.collection.insertOne() Insert a single document.
db.collection.find() Query documents.
db.collection.updateOne() Update a single document.
db.collection.deleteOne() Delete a single document.

Practical Guides to Node.js Snippets and Examples.



Follow us on Facebook and Twitter for latest update.