To connect to MongoDB from a Node.js application, you need to use a MongoDB client, with Mongoose being the most popular library for this purpose. Here’s how you can set up the connection using Mongoose, assuming that MongoDB is already installed (either locally or using MongoDB Atlas), and that Node.js is properly set up.
First, make sure you have the necessary packages installed in your Node.js project. You’ll need Express (for handling HTTP requests) and Mongoose (for interacting with MongoDB).
If you haven’t installed them yet, do so by running:
npm install express mongoose
server.js
fileThis will be the entry point for your Node.js application. Inside this file, you will connect to MongoDB using Mongoose.
const express = require('express'); const mongoose = require('mongoose'); // Create an Express app const app = express(); // Middleware to parse JSON requests app.use(express.json()); // MongoDB URI // Replace the URI with your own MongoDB connection string // For local MongoDB: // const mongoURI = 'mongodb://localhost:27017/myapp'; // For MongoDB Atlas: const mongoURI = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/myapp'; // Connect to MongoDB using Mongoose mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log('Connected to MongoDB...')) .catch((err) => console.error('Error connecting to MongoDB:', err)); // Define a simple route to test the connection app.get('/', (req, res) => { res.send('Hello, MongoDB with Node.js!'); }); // Start the Express server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}...`); });
You need to provide a connection URI for MongoDB. This URI contains the database location and credentials.
If MongoDB is running locally, the URI would look like this:
const mongoURI = 'mongodb://localhost:27017/myapp';
If you’re using MongoDB Atlas (cloud), you’ll get the connection URI after setting up a cluster. It will look something like this:
const mongoURI = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/myapp';
Replace <username>
and <password>
with your actual MongoDB credentials. The <dbname>
(in this case, myapp
) refers to the name of the database you wish to connect to.
In the example above, the mongoose.connect()
function is used to establish a connection to MongoDB. The two options used here, useNewUrlParser
and useUnifiedTopology
, are to avoid deprecation warnings and ensure a stable connection:
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log('Connected to MongoDB...')) .catch((err) => console.error('Error connecting to MongoDB:', err));
Mongoose emits several events that can be useful for managing and debugging your connection. You can listen to these events to get more details about the connection status.
Example:
mongoose.connection.on('connected', () => { console.log('Mongoose connected to MongoDB'); }); mongoose.connection.on('error', (err) => { console.log('Mongoose connection error:', err); }); mongoose.connection.on('disconnected', () => { console.log('Mongoose disconnected'); });
To verify that your MongoDB connection works, you can create a simple route that makes a query to the database.
Here’s how you can test it by querying a MongoDB collection after establishing the connection:
User
model: Define the schema for a user document and create the model to interact with MongoDB.// userModel.js const mongoose = require('mongoose'); // Define the User schema const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: { type: Number, required: true }, }); // Create the User model const User = mongoose.model('User', userSchema); module.exports = User;
Now, you can create a simple route to query all users from the database and return them in the response.
const User = require('./userModel'); // Import the User model // Route to get all users app.get('/users', async (req, res) => { try { const users = await User.find(); // Retrieve all users from the database res.status(200).json(users); // Send the users as a JSON response } catch (err) { res.status(500).send('Error retrieving users'); } });
Once you’ve set up the connection and routes, you can run the server:
node server.js
/
should return “Hello, MongoDB with Node.js!”./users
should return the list of users (if you have any in the database).At this point, you have successfully connected MongoDB to your Node.js application. The steps outlined above allow you to:
This is just the foundation—once the connection is established, you can start building more complex routes and functionality around your MongoDB database (e.g., creating users, updating documents, deleting records, etc.).