"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > MongoDB Integration with Node.js – A Complete Guide

MongoDB Integration with Node.js – A Complete Guide

Published on 2024-11-07
Browse:152

Integração do MongoDB com Node.js – Um Guia Completo

MongoDB is one of the most popular NoSQL databases, widely used by developers to create scalable and flexible applications. Together with Node.js, which is a widely adopted platform for backend development, you can build efficient APIs and robust applications. In this blog post, we'll explore how to configure MongoDB with Node.js, from installation to performing basic CRUD (Create, Read, Update, Delete) operations.


1. What is MongoDB?

MongoDB is a document-oriented NoSQL database. Instead of storing data in tables, as in relational databases, MongoDB stores documents in JSON format, which is called BSON (Binary JSON). This provides flexibility in data modeling and facilitates horizontal scalability.

2. Why use MongoDB with Node.js?

  • Native JSON: Node.js uses JavaScript, and MongoDB stores data in JSON format. This combination results in a smooth and efficient integration.
  • Scalability: MongoDB is highly scalable and ideal for modern applications that need to grow quickly.
  • Performance: With its document structure, MongoDB is optimized for fast reads, writes, and dynamic queries.
  • Community: Both MongoDB and Node.js have an active community, ensuring abundant resources and frequent updates.

3. Configuring MongoDB with Node.js

Step 1: Install MongoDB

First of all, you need to install MongoDB. Depending on your operating system, follow the instructions on the official MongoDB Installation website.

Step 2: Create a Node.js project

Create a new directory for your project and start a Node.js project:

mkdir mongo-node-app
cd mongo-node-app
npm init -y
Step 3: Install the MongoDB driver

The next step is to install the official MongoDB driver for Node.js:

npm install mongodb
Step 4: Connect to MongoDB

Now, create an index.js file to configure the connection to MongoDB. We will use MongoClient to connect to the database.

const { MongoClient } = require('mongodb');

async function connectDB() {
    const uri = "mongodb://localhost:27017"; // URL do MongoDB local
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        await client.connect();
        console.log("Conectado ao MongoDB");

        const db = client.db("mydatabase");
        return db;
    } catch (err) {
        console.error("Erro ao conectar ao MongoDB", err);
    } finally {
        // Fechar a conexão
        await client.close();
    }
}

connectDB();

4. CRUD Operations with MongoDB

1. Create

To add documents to the collection, we can use the insertOne() or insertMany() method.

async function createDocument(db) {
    const collection = db.collection("users");

    const newUser = {
        name: "Lucas",
        age: 25,
        email: "[email protected]"
    };

    const result = await collection.insertOne(newUser);
    console.log(`Documento inserido com o ID: ${result.insertedId}`);
}
2. Read

To search for documents in a collection, we use find() or findOne().

async function readDocuments(db) {
    const collection = db.collection("users");

    const users = await collection.find({ age: { $gte: 18 } }).toArray();
    console.log(users);
}
3. Update

To update a document, we use updateOne() or updateMany().

async function updateDocument(db) {
    const collection = db.collection("users");

    const result = await collection.updateOne(
        { name: "Lucas" },
        { $set: { email: "[email protected]" } }
    );

    console.log(`Documentos atualizados: ${result.modifiedCount}`);
}
4. Delete

To remove documents, we use deleteOne() or deleteMany().

async function deleteDocument(db) {
    const collection = db.collection("users");

    const result = await collection.deleteOne({ name: "Lucas" });
    console.log(`Documentos deletados: ${result.deletedCount}`);
}

5. Improving the Project Structure

For a large-scale project, it is better to modularize the MongoDB connection and CRUD operations. For example, we can have a separate connection module and dedicated services for each entity.

Modular Connection Example
// db.js
const { MongoClient } = require('mongodb');

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function connectDB() {
    await client.connect();
    const db = client.db("mydatabase");
    return db;
}

module.exports = { connectDB };
Using the Connection Module
// index.js
const { connectDB } = require('./db');

async function main() {
    const db = await connectDB();

    // Executar operações de CRUD
    await createDocument(db);
    await readDocuments(db);
    await updateDocument(db);
    await deleteDocument(db);
}

main();

6. Conclusion

MongoDB and Node.js form a powerful combination for building scalable APIs and modern web applications. With the flexibility of MongoDB and the JavaScript environment of Node.js, you can manipulate data quickly and efficiently. This guide provides a solid foundation for integrating MongoDB into your Node.js project, from initial configuration to CRUD operations.

If you want to dive deeper into the subject, consider exploring more features like indexing, aggregations, and replication in MongoDB.


Final Tips:

  • Mongoose: Although the official driver is efficient, libraries like Mongoose offer a friendlier abstraction with schemas and validation.
  • Scalability: Consider partitioning and replication in production to scale your application with MongoDB.

I hope this guide was helpful in integrating MongoDB with Node.js!

Release Statement This article is reproduced at: https://dev.to/lucaspereiradesouzat/integracao-do-mongodb-com-nodejs-um-guia-completo-39mk?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3