With MongoDB, a highly scalable and flexible NoSQL database, you can easily connect from Node.js using the mongodb
package. Here I will show you step by step how to do it:
How to connect Node.js to MongoDB
First, make sure you have Node.js installed on your system. Then, 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.
Step 2: Creation of the Connection File
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'; // Your database name
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 obtain a connection to the database and perform operations such as searching for documents, inserting new data, updating records, etc.
Let’s see an example:
import connect from './dbConnection.mjs';
async function fetchData() {
const db = await connect();
try {
const collection = db.collection('mi_coleccion');
const result = await collection.find({}).toArray();
console.log('Documents obtained:', result);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
db.close();
}
}
fetchData();
In this example, we are getting all the documents from the collection 'mi_coleccion'
and displaying the result in the console.
CRUD Operations
Once we have the connection file, we can use it to perform CRUD (Create, Read, Update, Delete) operations in our MongoDB database from Node.js.
Data Creation
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mi_base_de_datos';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('mi_coleccion');
const newDocument = { name: 'Example', age: 30 };
collection.insertOne(newDocument, (err, result) => {
if (err) throw err;
console.log('Document inserted successfully');
client.close();
});
});
Data Reading
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mi_base_de_datos';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('mi_coleccion');
collection.find({}).toArray((err, docs) => {
if (err) throw err;
console.log('Documents found:');
console.log(docs);
client.close();
});
});
Data Update
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mi_base_de_datos';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('mi_coleccion');
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();
});
});
Data Deletion
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mi_base_de_datos';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('mi_coleccion');
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