NodeJs MongoDB



 

Node.js MongoDB: A Guide to Using MongoDB with Node.js

MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format, making it ideal for applications that require a scalable and schema-less design. When combined with Node.js, developers can create powerful applications that leverage the strengths of both technologies.


Prerequisites

Ensure you have the following:

  1. Node.js: Installed from nodejs.org.
  2. MongoDB: Installed and running, or use a cloud service like MongoDB Atlas.
  3. MongoDB Driver for Node.js: Installed in your Node.js project.

Step 1: Set Up the Project

  1. Create a project directory (if not already done):

    bash
    mkdir node-mongodb
    cd node-mongodb
    
  2. Initialize a Node.js project:

    bash
    npm init -y
    
  3. Install the MongoDB driver:

    bash
    npm install mongodb
    

Step 2: Connect to MongoDB

  1. Create a file named app.js:

    bash
    touch app.js
    
  2. Open app.js and add the following code to connect to the MongoDB server:

    javascript
    const { MongoClient } = require('mongodb');
    
    // Replace the following with your MongoDB connection string
    const uri = 'mongodb://localhost:27017';
    const client = new MongoClient(uri);
    
    async function run() {
        try {
            // Connect to the MongoDB cluster
            await client.connect();
            console.log('Connected to MongoDB');
    
            // Perform operations here...
    
        } catch (error) {
            console.error('Error connecting to MongoDB:', error);
        } finally {
            // Close the connection
            await client.close();
        }
    }
    
    run().catch(console.error);
    

Step 3: Create a Database and Collection

To work with MongoDB, you need to create a database and a collection. Collections are similar to tables in relational databases.

  1. Create a database and collection:

    You can modify the run function to create a database and a collection:

    javascript
    const dbName = 'mydatabase';
    const collectionName = 'users';
    
    async function run() {
        try {
            await client.connect();
            console.log('Connected to MongoDB');
    
            const database = client.db(dbName);
            const collection = database.collection(collectionName);
    
            console.log(`Database: ${dbName}, Collection: ${collectionName}`);
    
            // Perform operations here...
    
        } catch (error) {
            console.error('Error connecting to MongoDB:', error);
        } finally {
            await client.close();
        }
    }
    

Step 4: Insert Documents into the Collection

You can insert documents (similar to rows in SQL) into the MongoDB collection:

javascript
async function run() {
    try {
        await client.connect();
        console.log('Connected to MongoDB');

        const database = client.db(dbName);
        const collection = database.collection(collectionName);

        // Insert a single document
        const user = { name: 'Alice', email: '[email protected]' };
        const result = await collection.insertOne(user);
        console.log(`Inserted document with _id: ${result.insertedId}`);

        // Insert multiple documents
        const users = [
            { name: 'Bob', email: '[email protected]' },
            { name: 'Charlie', email: '[email protected]' }
        ];
        const insertManyResult = await collection.insertMany(users);
        console.log(`${insertManyResult.insertedCount} documents were inserted`);
        
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    } finally {
        await client.close();
    }
}

Step 5: Retrieve Documents from the Collection

You can retrieve documents using the find method:

javascript
async function run() {
    try {
        await client.connect();
        console.log('Connected to MongoDB');

        const database = client.db(dbName);
        const collection = database.collection(collectionName);

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

        // Find a specific user
        const user = await collection.findOne({ name: 'Alice' });
        console.log('Found User:', user);

    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    } finally {
        await client.close();
    }
}

Step 6: Update Documents

You can update existing documents in the collection using the updateOne or updateMany methods:

javascript
async function run() {
    try {
        await client.connect();
        console.log('Connected to MongoDB');

        const database = client.db(dbName);
        const collection = database.collection(collectionName);

        // Update a specific user
        const result = await collection.updateOne(
            { name: 'Alice' }, // Filter
            { $set: { email: '[email protected]' } } // Update
        );

        console.log(`${result.modifiedCount} document(s) were updated`);
        
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    } finally {
        await client.close();
    }
}

Step 7: Delete Documents

You can delete documents using the deleteOne or deleteMany methods:

javascript
async function run() {
    try {
        await client.connect();
        console.log('Connected to MongoDB');

        const database = client.db(dbName);
        const collection = database.collection(collectionName);

        // Delete a specific user
        const result = await collection.deleteOne({ name: 'Bob' });
        console.log(`${result.deletedCount} document(s) were deleted`);

    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    } finally {
        await client.close();
    }
}

Step 8: Run the Application

To run the Node.js script and perform CRUD operations, execute the following command in your terminal:

bash
node app.js

You will see the results of the CRUD operations in the console.


Conclusion

In this guide, you’ve learned how to:

  • Set up a Node.js project to connect to MongoDB.
  • Perform basic CRUD operations: Create, Read, Update, and Delete documents in a MongoDB collection.
  • Understand how to structure your Node.js application to interact with MongoDB effectively.