The MongoDB Node.js driver is a powerful tool that allows developers to interact with MongoDB databases directly from their Node.js applications. This tutorial will walk you through the process of setting up and using the MongoDB Node.js driver, including connecting to a database, performing CRUD operations, and handling errors.
Before we begin, ensure you have the following installed:
First, create a new directory for your project and initialize it with npm.
mkdir mongodb-nodejs-driver-example
cd mongodb-nodejs-driver-example
npm init -y
Next, install the MongoDB Node.js driver using npm:
npm install mongodb
To connect to a MongoDB database, you need to use the MongoClient class provided by the MongoDB Node.js driver. Here's how you can do it:
// Import MongoClient from the mongodb package
const { MongoClient } = require('mongodb');
// Connection URI - replace with your MongoDB connection string
const uri = 'mongodb://localhost:27017';
// Create a new MongoClient
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
// Connect the client to the server
await client.connect();
console.log('Connected successfully to MongoDB');
const database = client.db('mydatabase');
const collection = database.collection('documents');
// Perform operations on the collection here
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
'mongodb://localhost:27017' with your actual connection string if you're connecting to a remote server.To insert documents into a collection, use the insertOne or insertMany methods:
async function run() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const database = client.db('mydatabase');
const collection = database.collection('documents');
// Insert one document
const insertResult = await collection.insertOne({ name: 'Alice', age: 30 });
console.log('Inserted document:', insertResult.insertedId);
// Insert multiple documents
const documents = [
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
const insertManyResult = await collection.insertMany(documents);
console.log('Inserted documents:', insertManyResult.insertedIds);
} finally {
await client.close();
}
}
run().catch(console.dir);
To query documents, use the find method:
async function run() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const database = client.db('mydatabase');
const collection = database.collection('documents');
// Find all documents
const queryResult = await collection.find({}).toArray();
console.log('Found documents:', queryResult);
// Find a specific document
const specificQueryResult = await collection.findOne({ name: 'Alice' });
console.log('Found document:', specificQueryResult);
} finally {
await client.close();
}
}
run().catch(console.dir);
To update documents, use the updateOne or updateMany methods:
async function run() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const database = client.db('mydatabase');
const collection = database.collection('documents');
// Update one document
const updateResult = await collection.updateOne(
{ name: 'Alice' },
{ $set: { age: 31 } }
);
console.log('Updated document:', updateResult.matchedCount);
// Update multiple documents
const updateManyResult = await collection.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } }
);
console.log('Updated documents:', updateManyResult.matchedCount);
} finally {
await client.close();
}
}
run().catch(console.dir);
To delete documents, use the deleteOne or deleteMany methods:
async function run() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const database = client.db('mydatabase');
const collection = database.collection('documents');
// Delete one document
const deleteResult = await collection.deleteOne({ name: 'Alice' });
console.log('Deleted document:', deleteResult.deletedCount);
// Delete multiple documents
const deleteManyResult = await collection.deleteMany({ age: { $gt: 30 } });
console.log('Deleted documents:', deleteManyResult.deletedCount);
} finally {
await client.close();
}
}
run().catch(console.dir);
Proper error handling is crucial for maintaining robust applications. Here's how you can handle errors when using the MongoDB Node.js driver:
async function run() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const database = client.db('mydatabase');
const collection = database.collection('documents');
// Example operation that might throw an error
const result = await collection.findOne({ nonExistentField: 'value' });
console.log(result);
} catch (error) {
console.error('An error occurred:', error);
} finally {
await client.close();
}
}
run().catch(console.dir);
The MongoDB Node.js driver provides a comprehensive set of tools for interacting with MongoDB databases from Node.js applications. By following the steps outlined in this tutorial, you should be able to connect to your MongoDB instance, perform CRUD operations, and handle errors effectively. Remember to refer to the official MongoDB documentation for more advanced features and best practices.