Making REST API Using Nodejs with MongoDB

Making REST API Using Nodejs with MongoDB

Application of Nodejs and MongoDB

In this tutorial, I'll show you how to interact with a MongoDB database from Node.js.

Using MongoDB and Node.js

MongoDB is one of the most popular databases used along with Node.js.

We’ll be using the official MongoDB npm package. If you already have a Node.js project you are working on, install it using

First, ensure your system has Node.js version 12 or later and a compatible version of npm (Node Package Manager). For more installation proceed to the official Node.js website.

Once this do make a new folder and run the command

npm init

to initialize an empty nodejs project. After this will install MongoDB using the below command.

npm install mongodb

To start using MongoDB in your web application you need to first connect your application with the MongoDb server so that you can use all functionalists of a MongoDB.

Connecting to MongoDB

You require the MongoDB package and you get the MongoClient object from it. Create a new file server.js to start our Express.js server. Load mongoose and express by adding the following code to server.js.

const express = require("express");
const mongoose = require("mongoose");
const Router = require("./routes")

const app = express();

app.use(express.json());

Then connect to a local MongoDB instance using the mongoose.connect() function.

server.js

mongoose.connect('mongodb://localhost:27017/usersdb',
  {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  }
);

To create a connection to the MongoDB atlas, we have to create a new MongoDB cluster.

Visit the MongoDB atlas website and follow the below steps.

  1. Open your Cluster tab in MongoDB Atlas and click CONNECT.
  2. Select Connect your application and choose Node.js for the driver.
  3. Copy the connection string.

With the connection at hand, create the following variables and replace their values using your actual credentials.

server.js

const username = "<mongodb username>";
const password = "<password>";
const cluster = "<cluster name>";
const dbname = "myFirstDatabase";

mongoose.connect(
  `mongodb+srv://${username}:${password}@${cluster}.mongodb.net/${dbname}?retryWrites=true&w=majority`, 
  {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  }
);

To check that everything is working as expected, add the following code right below mongoose.connect()

server.js

// ...
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
  console.log("Connected successfully");
});

Then, set the app to listen to port 3000.

This way we can connect any Nodejs application with MongoDB. It is easy to use with lots of flexibility in hand.

Now to upload any data to MongoDB we have to create something called schema. Which is a basic layout of how the data will look like.

Creating the schema

Now let’s define a collection schema for our application.

Create another file models.js and add the following code.

models.js

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  age: {
    type: Number,
    default: 0,
  },
});

const User = mongoose.model("User", UserSchema);

module.exports = User;

We create a schema UserSchema using the mongoose.Schema() method. The schema collects the name and age fields sent from the request.

POST endpoint to send data to MongoDB

Create a new file routes.js. This file defines the endpoints for our app.

Load express and the schema we created in Step 3 by adding the following code.

routes.js

const express = require("express");
const userModel = require("./models");
const app = express();

Then create the POST endpoint by adding the following code.

routes.js

// ...
app.post("/add_user", async (request, response) => {
    const user = new userModel(request.body);

    try {
      await user.save();
      response.send(user);
    } catch (error) {
      response.status(500).send(error);
    }
});

We create a route /add_user to add a new user to the database. We parse the content to be saved to the database using the line const user = new userModel(request.body);.

We then use a try/catch block to save the object to the database using the .save() method.

To find any element using async/await

const find = async () => {
  try {
    const item = await collection.findOne({name: 'Togo'})
  } catch(err => {
  console.error(err)
  })
}

find()

Conclusion

We have looked at how to connect a Nodejs application with MongoDB. We have also looked at how to establish MongoDB schemes and POST requests for our collections.