Home >Web Front-end >JS Tutorial >MongoDB Integration with Node.js – A Complete Guide
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.
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.
First of all, you need to install MongoDB. Depending on your operating system, follow the instructions on the official MongoDB Installation website.
Create a new directory for your project and start a Node.js project:
mkdir mongo-node-app cd mongo-node-app npm init -y
The next step is to install the official MongoDB driver for Node.js:
npm install 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();
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}`); }
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); }
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}`); }
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}`); }
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.
// 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 };
// 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();
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:
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!