How to connect MongoDB with NodeJS Express using Mongoose

How to connect MongoDB with NodeJS Express using Mongoose

Table of contents

No heading

No headings in the article.

Step 1: Install Dependencies To start with, you will need to have Node.js and npm installed on your system. If you don't have them, you can download and install them from the official Node.js website.

Once you have Node.js and npm installed, you need to create a new project directory and navigate to it in your terminal. Once you are inside the project directory, you can run the following command to create a new package.json file:

npm init -y

This command will create a new package.json file with default values.

Next, you need to install the necessary dependencies for this project. Run the following command to install the dependencies:

npm install express mongoose

Step 2: Create a MongoDB Database Before you can connect to a MongoDB database, you need to create one. You can create a new MongoDB database by signing up for a free MongoDB Atlas account. MongoDB Atlas provides a free tier for developers to get started with.

Once you have signed up for MongoDB Atlas, you can create a new cluster and a new database. Make sure to note down the connection string for the database, as you will need it later in this guide.

Step 3: Connect to the MongoDB Database To connect to the MongoDB database, you need to create a new file called app.js in your project directory. Add the following code to the file:

const express = require('express');
const mongoose = require('mongoose');

const app = express();

mongoose.connect('<your-mongodb-connection-string>', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
  .then(() => console.log('Connected to MongoDB...'))
  .catch(err => console.error('Could not connect to MongoDB...', err));

app.listen(3000, () => console.log('Server running on port 3000...'));

In this code, we require the Express and mongoose libraries, create a new Express application, and connect to the MongoDB database using mongoose.connect() function. Make sure to replace <your-mongodb-connection-string> it with the actual connection string for your database.

The useNewUrlParser and useUnifiedTopology options are used to avoid deprecation warnings when connecting to the database.

Finally, we start the Express server and listen on port 3000.

Step 4: Create a Mongoose Schema Before we can start using MongoDB, we need to define a schema for our data. A schema is a blueprint that defines the structure of a document in a MongoDB collection.

Create a new file called model.js in your project directory and add the following code:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
});

module.exports = mongoose.model('User', userSchema);

In this code, we define a new Mongoose schema for a user document with three fields: name, email, and password. We export the schema as a Mongoose model with the name 'User'.

Step 5: Create a Route to Save Data to MongoDB Now that we have connected to the MongoDB database and defined a schema for our data, we can create a route to save data to the database.

In your app.js file, add the following code:

const express = require('express');
const mongoose = require('mongoose');
const User = require('./model');

const app = express();

mongoose.connect('<your-mongodb-connection-string>', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
  .then(() => console.log('Connected to MongoDB...'))
  .catch(err => console.error('Could not connect to MongoDB...',

In this code, we require the User model we defined in the model.js file. We create a new route to handle a POST request to /users. When this route is called, we create a new user object using the User model and save it to the database using the save() method.

Step 6: Test the Route To test the route, start the server by running the following command in your terminal:

Copy codenode app.js

Then, send a POST request to localhost:3000/users with a JSON body containing the user data:

perlCopy code{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123"
}

You should see the message "User saved to database!" in your terminal, indicating that the data was successfully saved to the MongoDB database.

Step 7: Retrieve Data from MongoDB Now that we have saved data to the database, let's retrieve it. Add the following code to your app.js file:

csharpCopy codeapp.get('/users', async (req, res) => {
  const users = await User.find();
  res.send(users);
});

In this code, we create a new route to handle a GET request to /users. When this route is called, we use the find() method of the User model to retrieve all users from the database. We then send the list of users back to the client as a JSON response.

Step 8: Test the Route To test the route, start the server by running the following command in your terminal:

Copy codenode app.js

Then, send a GET request to localhost:3000/users. You should see a JSON response containing the list of users you saved earlier:

cssCopy code[  {    "_id": "60b3e1f20d74b01e84c9d07d",    "name": "John Doe",    "email": "john@example.com",    "password": "password123",    "__v": 0  }]

Congratulations! You have successfully connected MongoDB with Node.js Express using Mongoose and saved/retrieved data from the database. You can now build more complex applications that leverage the power and flexibility of MongoDB.

If you have any problem regarding to this, you ask me in the comment section

Thank you for reading :)

Did you find this article valuable?

Support Aman Yadav by becoming a sponsor. Any amount is appreciated!