DEV Community

Cover image for How to use MongoDB in Node.js application
Raj Jeswal
Raj Jeswal

Posted on

How to use MongoDB in Node.js application

Prerequisites

This tutorial assumes that you have the following:

  • Basic knowledge of Node
  • Node installed on your machine
  • Any code or text editor of your choice
  • MongoDB installed locally

MongoDB is an open-source non-relational document database and leading NoSQL database that provides support for JSON-like storage.

Basic terms also change in SQL and NoSQL based databases to map data, since in Sql based database you have tables but nosql database has collections, SQL based database has rows but nosql database has documents, SQL based database has columns but nosql database has fields, Sql based database has relationships, but nosql database has linked and embedded documents.

Connecting MongoDB with your application using Mongoose, Mongoose is an object document mapper (ODM) used to establish a connection to the MongoDB database in NodeJS.

install mongoose on your project via this command.

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

Before launching your server, add the following code:

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/< DB Name >', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function () {
  console.log('Connected to Mongoose');
});
Enter fullscreen mode Exit fullscreen mode

module.exports = db;

When you restart your Node.js server, you should see in your terminal "Connected to MongoDB database" if your connection is well established. Otherwise, a message containing the error if the connection could not be established.

Running Queries With Mongoose

Mongoose requires you to define its schemas before manipulating its objects. Let's start by creating the first schema in a user.js file.

const { Schema, model } = require('mongoose');

const userSchema = new Schema({
    firstName:  String,
    lastName: String,
    email:   String,
  });

const User = model('User', userSchema);

module.exports = User;
Enter fullscreen mode Exit fullscreen mode

This file will contain the User module, which is a mongoose schema. We have the properties that a user can contain. Once this schema is defined, you can now use the mongoose schema methods to perform our create, read, update, or delete operations (CRUD functionality).

const User = require('./user.js');

Create a user

app.post('/users', async (req, res) => {
  try {
    let { firstname, lastname, email } = req.body;

    const user = await new User({ firstname, lastname, email });

    const result = await user.save();

    return res.status(201).json({ status: true, data: result });
  } catch (error) {
    res.status(500).json({ status: false, errors: error });
  }
});
Enter fullscreen mode Exit fullscreen mode

List all users

app.get('/users', async (req, res) => {
  try {
    const user = await User.find();
    return res.status(200).json({ status: true, data: user });
  } catch (error) {
    res.status(500).json({ status: false, errors: error });
  }
});
Enter fullscreen mode Exit fullscreen mode

Pick a user

app.get('/users/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    return res.status(200).json({ status: true, data: user });
  } catch (error) {
    res.status(500).json({ status: false, errors: error });
  }
});
Enter fullscreen mode Exit fullscreen mode

Update a user

app.put('/users/:id', async (req, res) => {
  try {
    let { firstname, lastname, email } = req.body;

    const user = await User.findOne({ _id: req.params.id });

    if (!user) return res.status(404).json({ status: false, error: 'No User' });

    user.firstname = firstname ? firstname : user.firstname;
    user.lastname = lastname ? lastname : user.lastname;
    user.email = email ? email : user.email;

    const updatedUser = await user.save();

    return res.status(200).json({ status: true, data: updatedUser });
  } catch (error) {
    res.status(500).json({ status: false, errors: error });
  }
});
Enter fullscreen mode Exit fullscreen mode

Delete a user

app.delete('/users/:id', async (req, res) => {
  try {
    const user = await User.findOne({ _id: req.params.id });

    if (!user) return res.status(404).json({ status: false, error: 'No User' });

    await user.remove();
    return res
      .status(200)
      .json({ status: true, msg: 'User deleted successfully!' });
  } catch (error) {
    console.log(error);
    res.status(500).json({ status: false, errors: error });
  }
});
Enter fullscreen mode Exit fullscreen mode

conclusion

We learned how to use Mongoose ODM to connect to the Mongodb database in our Node.js project.

Feel free to check the code on GitHub Repository if you had any trouble following this tutorial.

If you have any questions or comments about this article, please do not hesitate to reach out.

Thank you for reading.

Credits

MongoDB, Built by developers, for developers: https://www.mongodb.com/

Mongoose, is a MongoDB object modeling tool: https://mongoosejs.com/

Top comments (0)