Home  >  Article  >  Web Front-end  >  MongoDB Integration with Node.js – A Complete Guide

MongoDB Integration with Node.js – A Complete Guide

Patricia Arquette
Patricia ArquetteOriginal
2024-10-13 06:19:02309browse

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 will 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 features 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: "lucas@example.com"
    };

    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: "lucas.new@example.com" } }
    );

    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 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!

The above is the detailed content of MongoDB Integration with Node.js – A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn