How to use express with mongoose

Introduction

Express is an important part of web application development stacks such as MEAN and MERN stack. Developing web applications is not an easy task. Backend is an important part of every web application. The backend is the connectivity to databases and it also holds APIs that interact with the databases. One important part of the backend is creating a server. Express provides flexibility here. It also provides many other options while working with Nodejs. It is also flexible with mongoose. In this article, we will discuss how to use express with mongoose.

What is express?

Express is a minimalist and extensible web framework that is built for Nodejs. Using express, we can create better servers that are readable, easy to handle and manage.

Installing express and mongoose

Express is available in Node Package Manager. Create a new folder and name it anything you like. Open a terminal and move to that folder. We need a package.json file to start. So run the following command.

npm init -y

Now, we can install the express and mongoose.

npm install --save express
npm install mongoose

Also, install the nodemon to run the server.

npm install nodemon

We are ready to go now. We will create an application that will retrieve data from a MongoDB database using Express, Nodejs, and mongoose.

Creating a server

The first step is to create a server using express. As mentioned earlier, creating a server with express is a simple task. We will do it step by step for better understanding. Create a new file and name it ‘server.js’.

To use the express in our file, we need to import it.

var express = require("express");

The next step is to have an instance of express.

var app = express();

Now we have the instance of express, we can use the listen() method to create a server. The listen() method has two parameters – a port number and a callback function.

app.listen(4000, () => {
  console.log("Server running on localhost 4000");
});

Let’s test it by using the nodemon.

Image from Gyazo

Using mongoose with express

Let’s use mongoose with express. We will use mongoose to retrieve documents from the kennel collection.

This is how server.js file looks like.

const express = require("express");
const app = express();

app.listen(4000, () => {
  console.log("Server running on localhost 4000");
});

First of all, we need a schema. Each document in the kennel collection has three fields – name, age, and breed. So, create a new file in the same folder and name it “model.js”.

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

let kennel = new Schema(
  {
    name: {
      type: String
    },
    age: {
      type: Number
    },
    breed: {
      type: String
    }
  },
  { collection: "kennel" }
);

module.exports = mongoose.model("kennels", kennel);

This is the schema. We also exported the schema because we need it in the server.js file. Now, open the server.js file and import the schema in it.

var kennel = require("./model.js");

We have schema imported in the file. We will use this later but before that, let’s create a connection with the MongoDB database. For a connection, first, we need to import mongoose in the server.js file.

const mongoose = require("mongoose");

We need the URI that will specify the database in the localhost.

var uri = "mongodb://127.0.0.1:27017/kennel";

Here, ‘127.0.0.1’ is the localhost and ‘27017’ is the default port on which MongoDB runs. ‘kennel’ is the name of the database.

Finally, we can connect to MongoDB using the connect() method. The URI we created will be the first parameter of this method.

mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

The second parameter is an object to avoid warnings. We have the URI and the connect() method in place. Now we can establish a connection.

const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

We created a server using express. Then, we created a schema using mongoose and imported it in the server.js file. We will use the schema later when we will create a route handler. We also establish a connection with the database using mongoose. This is how server.js looks like for the time being.

const mongoose = require("mongoose");
const express = require("express");
const app = express();
var kennel = require("./model.js");

var uri = "mongodb://127.0.0.1:27017/kennel";
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

app.listen(4000, () => {
  console.log("Server running on localhost 4000");
});

Let’s run the server and check if the connection is established successfully or not.

Image from Gyazo

The server is running on port 4000 and connection with MongoDB is also established successfully.

Retrieving data

To retrieve data from the kennel collection, we need a router and a route handler. So let’s create a router using express.

const router = express.Router();

The next step is to use this router in the file.

app.use("/", router);

Now we can create a route handler. Remember, we are going to fetch data, so we will make a GET request.

router.route("/fetchdata").get(function(req, res) {});

This route handler will be invoked when the endpoint ‘/fetchdata’ is executed. To fetch the documents, we will use the find() method.

router.route("/fetchdata").get(function(req, res) {
  kennel.find({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Let’s execute this route handler using the postman tool and check if it works properly or not.

Image from Gyazo

Yes! Everything works fine.

Conclusion

This concludes our tutorial on how to use express with mongoose. Thank you for joining us for another Object Rocket knowledge-base tutorial.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.