Connect MongoDB with NodeJS & Express

Connect MongoDB with NodeJS & Express

At 5/26/2023

1 - Install the necessary dependencies:

You will need to install the mongodb and mongoose npm packages. You can install them using the following command:

$npm install mongodb mongoose

2 - Set up the database connection:

In your Express application, you will need to create a database connection using Mongoose. You can do this by creating a mongoose object and using its connect() method to connect to your database. Here's an example:

const mongoose = require('mongoose');
const uri = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("Connected to database");
});

In the example above, we create a mongoose object and connect to a local MongoDB database called mydatabase. We also set up a listener for the open event, which indicates that the connection was successful.

3- Define a schema for your data:

Before you can start using MongoDB in your Express application, you need to define a schema for your data. This defines the structure of your data and the types of values that are allowed. You can do this using the mongoose.Schema() method. Here's an example:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    age: Number
});
const User = mongoose.model('User', userSchema);
module.exports = User;

In the example above, we define a schema for a User object with a name, email, and age field. We also create a model from the schema using the mongoose.model() method, and export it so that it can be used in other parts of our application.

4 - Use the database in your Express routes:

Once you have set up your database connection and defined your data schema, you can use MongoDB in your Express routes. Here's an example:

const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.get('/users', (req, res) => {
    User.find((err, users) => {
        if (err) {
            console.error(err);
            res.status(500).send("Error retrieving users from database");
        } else {
            res.json(users);
        }
    });
});
module.exports = router;

In the example above, we define a route that retrieves all users from the database using the User.find() method. If an error occurs, we send a 500 error response. Otherwise, we send a JSON response with the users.

Copyrights

We respect the property rights of others and are always careful not to infringe on their rights, so authors and publishing houses have the right to demand that an article or book download link be removed from the site. If you find an article or book of yours and do not agree to the posting of a download link, or you have a suggestion or complaint, write to us through the Contact Us, or by email at: support@freewsad.com.

More About us