MongoDB Integration in Node.js
Learn how to connect a Node.js application to MongoDB, create collections, insert documents, and retrieve data using the MongoDB Node.js driver.
MongoDB is a NoSQL document database. It stores data as documents in BSON format, which is similar to JSON. Documents are grouped into collections instead of traditional relational tables.
For example, an online shopping application can store product information in a MongoDB collection and retrieve it whenever a client requests product details.
1. What Is MongoDB?
MongoDB is a document-oriented NoSQL database. Instead of storing information in rows and columns, it stores documents containing fields and values.
For example, a product document may look like this:
{
"_id": 1,
"name": "Laptop",
"price": 50000,
"category": "Electronics"
}
Multiple product documents can be stored in a collection named
products.
| MongoDB Concept | Meaning |
|---|---|
| Database | Contains collections. |
| Collection | Groups related documents. |
| Document | Stores a record as fields and values. |
| Field | Represents an individual property, such as name or price. |
_id |
Identifies a document uniquely within its collection. |
2. SQL Tables vs MongoDB Collections
Relational databases organize records into tables. MongoDB organizes related documents into collections.
| Relational Database | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| SQL query | MongoDB query using the driver or query language |
3. Installing the MongoDB Driver
To connect Node.js to MongoDB, install the official MongoDB Node.js driver. Express can also be installed if you want to expose database operations through REST API endpoints.
npm init -y
npm install express mongodb
A basic project structure looks like this:
mongodb-node-app/
│
├── node_modules/
├── package.json
├── package-lock.json
└── app.js
4. Connecting Node.js to MongoDB
The MongoDB driver provides the MongoClient class
for connecting to a MongoDB deployment. Once connected, the
application can access a database and its collections.
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
async function connectDatabase() {
try {
await client.connect();
console.log('Connected to MongoDB successfully!');
const database = client.db('nodejsdb');
console.log('Database selected:', database.databaseName);
} catch (error) {
console.error('MongoDB connection failed:', error.message);
}
}
connectDatabase();
Understanding the important parts:
| Code | Purpose |
|---|---|
MongoClient |
Creates a client for communicating with MongoDB. |
process.env.MONGODB_URI |
Reads the connection URI from an environment variable. |
client.connect() |
Establishes the database connection. |
client.db('nodejsdb') |
Selects the database named nodejsdb. |
try...catch |
Handles connection errors. |
5. Inserting a Document
MongoDB provides the insertOne() method to insert
a single document into a collection.
const { MongoClient } = require('mongodb');
async function insertProduct() {
const client = new MongoClient(process.env.MONGODB_URI);
try {
await client.connect();
const database = client.db('nodejsdb');
const products = database.collection('products');
const result = await products.insertOne({
name: 'Laptop',
price: 50000,
category: 'Electronics'
});
console.log('Inserted document ID:', result.insertedId);
} catch (error) {
console.error('Insert failed:', error.message);
} finally {
await client.close();
}
}
insertProduct();
If the insert succeeds, MongoDB creates an _id for
the document when one is not supplied. The insertedId property
contains the ID of the newly inserted document.
6. Retrieving Documents
Use find() to retrieve multiple documents and
findOne() to retrieve a single matching document.
const { MongoClient } = require('mongodb');
async function getProducts() {
const client = new MongoClient(process.env.MONGODB_URI);
try {
await client.connect();
const database = client.db('nodejsdb');
const products = database.collection('products');
const allProducts = await products.find({}).toArray();
console.log(allProducts);
} catch (error) {
console.error('Read failed:', error.message);
} finally {
await client.close();
}
}
getProducts();
The empty filter {} matches all documents in the collection.
The toArray() method collects the matching documents into
a JavaScript array.
Example output:
[
{
"_id": "generated MongoDB ObjectId",
"name": "Laptop",
"price": 50000,
"category": "Electronics"
}
]
7. Updating a Document
Use updateOne() to update fields in the first document
that matches a filter. The $set operator changes the
specified fields without replacing the entire document.
const result = await products.updateOne(
{ name: 'Laptop' },
{
$set: {
price: 55000
}
}
);
console.log('Matched documents:', result.matchedCount);
console.log('Modified documents:', result.modifiedCount);
In this example, the price of the first matching Laptop document is updated to 55000. The matchedCount and modifiedCount properties help identify the result of the operation.
8. Deleting a Document
Use deleteOne() to delete the first document matching
a filter. Always make sure the filter identifies the intended document.
const result = await products.deleteOne({
name: 'Laptop'
});
console.log('Deleted documents:', result.deletedCount);
If a matching document is found and deleted, deletedCount will usually be 1. If no document matches, it will be 0.
9. Complete Example: Express with MongoDB
The following example creates a simple REST API that retrieves products from MongoDB. It uses one MongoClient connection for the application and closes it when the server shuts down.
const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
app.use(express.json());
const client = new MongoClient(process.env.MONGODB_URI);
let products;
app.get('/api/products', async (req, res) => {
try {
const result = await products.find({}).toArray();
res.status(200).json(result);
} catch (error) {
console.error('Database query failed:', error.message);
res.status(500).json({
message: 'Unable to retrieve products'
});
}
});
async function startServer() {
try {
await client.connect();
const database = client.db('nodejsdb');
products = database.collection('products');
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
} catch (error) {
console.error('MongoDB connection failed:', error.message);
await client.close();
process.exit(1);
}
}
startServer();
async function shutdown() {
await client.close();
process.exit(0);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
Start the application:
node app.js
Send this GET request using Postman or a browser:
GET http://localhost:3000/api/products
If the connection succeeds, the endpoint returns the documents stored in the products collection.
10. MongoDB Integration Flow
Sends an HTTP request
Processes the request
Executes the database operation
Stores or retrieves documents
Returns the result to the client
Important Points to Remember
- MongoDB is a document-oriented NoSQL database.
- Documents are grouped into collections.
- Install the
mongodbpackage to use the official driver. - Use
MongoClientto connect to MongoDB. - Use
insertOne()to insert a document. - Use
find()andfindOne()to retrieve documents. - Use
updateOne()to update a matching document. - Use
deleteOne()to delete a matching document. - Protect connection strings and database credentials.
- Handle database errors and close resources properly.
Summary
MongoDB stores data as documents grouped into collections. Node.js applications can connect to MongoDB using the official MongoDB driver and perform insert, read, update, and delete operations. Express routes can expose these operations through REST API endpoints.
In the next lesson, we will learn how to perform CRUD operations in a Node.js database application.