We can easily connect Node.js to MongoDB, a highly scalable and flexible NoSQL database, you can easily connect from Node.js using the mongodb
package.
How to Connect Node.js to MongoDB
First, we install the mongodb
package using npm:
npm install mongodb
This package will allow us to connect and perform operations with the MongoDB database from Node.js.
Creating the Connection File
Now we create a file to handle the connection to MongoDB (for example dbConnection.mjs
). In this file, we will use the mongodb
module to connect to the database.
import { MongoClient } from 'mongodb';
const uri = 'mongodb://localhost:27017'; // Connection URL to your database
const dbName = 'mydatabase'; // Name of your database
async function connect() {
try {
const client = new MongoClient(uri);
await client.connect();
const db = client.db(dbName);
console.log('Connection to MongoDB established.');
return db;
} catch (error) {
console.error('Error connecting to MongoDB:', error);
throw error;
}
}
export default connect;
Make sure to replace 'mongodb://localhost:27017'
with the correct connection URL for your MongoDB database, and 'mydatabase'
with the name of your database.
Using the Connection in Your Application
Now that we have defined the connection function in dbConnection.mjs
, we can import it and use it anywhere in our application to perform operations with the MongoDB database.
For example, in another file of your application app.mjs
, we can use the connect
function to get a connection to the database and perform operations like searching for documents, inserting new data, updating records, etc.
Let’s see it with an example:
import connect from './dbConnection.mjs';
async function fetchData() {
const db = await connect();
try {
const collection = db.collection('my_collection');
const result = await collection.find({}).toArray();
console.log('Documents retrieved:', result);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
db.close();
}
}
fetchData();
In this example, we are retrieving all documents from the collection 'my_collection'
and displaying the result in the console.
CRUD Operations
Once we have the connection file, we can use it to perform CRUD operations (Create, Read, Update, Delete) on our MongoDB database from Node.js.
Creating Data
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'my_database';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('my_collection');
const newDocument = { name: 'Example', age: 30 };
collection.insertOne(newDocument, (err, result) => {
if (err) throw err;
console.log('Document inserted successfully');
client.close();
});
});
Reading Data
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'my_database';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('my_collection');
collection.find({}).toArray((err, docs) => {
if (err) throw err;
console.log('Documents found:');
console.log(docs);
client.close();
});
});
Updating Data
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'my_database';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('my_collection');
const filter = { name: 'Example' };
const newValue = { $set: { age: 35 } };
collection.updateOne(filter, newValue, (err, result) => {
if (err) throw err;
console.log('Document updated successfully');
client.close();
});
});
Deleting Data
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'my_database';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('my_collection');
const filter = { name: 'Example' };
collection.deleteOne(filter, (err, result) => {
if (err) throw err;
console.log('Document deleted successfully');
client.close();
});
});
Download the Code
All the code from this post is available for download on GitHub