In Node.js, To create a MongoDB connection in a Node.js application. we can use the MongoDB Node.js driver or Mongoose package.
First, install the MongoDB Node.js driver using npm if you haven't already:
npm install mongodb
In the Node.js application, import the MongoClient class from the "MongoDB" package and use it to connect to your MongoDB server.
const { MongoClient } = require('mongodb'); // Connection URI const uri = 'mongodb://localhost:27017'; // MongoDB default URI // Create a new MongoClient const client = new MongoClient(uri); // Connect to the MongoDB server client.connect((err) => { if (err) { console.error('Failed to connect to MongoDB:', err); return; } console.log('Connected successfully to MongoDB'); // Perform database operations here // Close the connection when done client.close(); });
Replace 'mongodb://localhost:27017' with your MongoDB connection string.
Ensure that it includes the correct hostname, port, and any other necessary options.
Handle any connection errors that may occur during the connection process.
Within the connect callback function, you can perform database operations such as inserting, updating, deleting, or querying documents.
Close the MongoDB connection when your application is done interacting with the database to avoid resource leaks.
Install the `Mongoose` package using npm.
npm install mongoose
In your Node.js application, import the "mongoose" package using the "require()" method.
const mongoose = require('mongoose');
Use the "mongoose.connect()" method to connect to your MongoDB database. we typically do this when our application starts up:
const uri = 'mongodb://localhost:27017/your_database_name'; // MongoDB connection string mongoose.connect(uri) .then(() => { console.log('Connected to MongoDB'); // Your code here }) .catch((err) => { console.error('Error connecting to MongoDB:', err); });
Replace 'mongodb://localhost:27017/your_database_name' with your MongoDB connection string.
We can listen to various events emitted by "Mongoose" to handle connection-related events.
mongoose.connection.on('connected', () => { console.log('Mongoose connected to MongoDB'); }); mongoose.connection.on('error', (err) => { console.error('Mongoose connection error:', err); }); mongoose.connection.on('disconnected', () => { console.log('Mongoose disconnected from MongoDB'); });
We should close the "Mongoose connection" when application exits or shuts down.
This code listens for the SIGINT signal (Ctrl+C) and closes the Mongoose connection before exiting the application.
process.on('SIGINT', () => { mongoose.connection.close(() => { console.log('Mongoose connection closed due to app termination'); process.exit(0); }); });
Once connected, we can define Mongoose models to interact with your MongoDB collections.
Models represent documents in a collection and provide an interface for querying and manipulating data.