How to Setup a NodeJS App with MongoDB using Mongoose

Introduction

NoSQL databases and running your app’s backend with Javascript have both become increasingly popular. In this tutorial we will show you how to use NodeJS to connect with MongoDB using the Mongoose library to setup the backend for a simple web application.

If you’re unfamiliar with these technologies, MongoDB is a NoSQL database technology and NodeJS allows you to run your backend using Javascript code. Mongoose is one of the two popular npm modules to interact with MongoDB in Javascript. The Mongoose module differentiates itself from the MongoJS module with a focus on giving you tools to create models and interact with your database through those models.

We won’t be showing you how to build a full app in this tutorial but just the basic setup so your Javascript can communicate to MongoDB using the npm library Mongoose. We’ll be using the Express framework ( another npm module ) to show how you to setup your routes.

If you just want the starter code jump to the end of the article for Just The Code.

Prerequisites

  • You should have MongoDB installed and running.
  • Some command line experience is recommended.

Setup Your Project

First create a folder for this project. We call ours demo but you can call it whatever you’d like

mkdir demo

Now navigate into that folder and create an app.js file which will act as our server.

cd demo
touch app.js

Add dependencies to your server file app.js

Next we’ll use the npm init command inside our demo project folder to allow npm to manage our dependencies. It will prompt you with a few questions but the defaults should all work for our application.

Now we need to add some dependency libraries to our app.js that will make our programming lives a whole lot easier.

  • First we install the npm library mongoose will make it easy to connect and communicate with MongoDB as well as create models for our data.
npm install mongoose
  • Next we’ll install the npm library express which is a popular framework to create web applications. It makes creating routes extremely easy. Again we use npm to install it.
npm install express

Now that we have them installed we’ll require them in our app.js file so that we can actually use them in javascript.

var express = require("express");
var mongoose = require("mongoose");

Setup Express

Now we’ll create a very basic express app and verify our server (app.js) will run and is listening for requests. The ammended app.js file looks like this now.

File: /demo/app.js `js var express = require(“express”); var mongoose = require(“mongoose”);

var PORT = 3000;

// 1. Initialize Express var app = express();

// Parse request body as JSON app.use(express.urlencoded({ extended: true })); app.use(express.json());

// 2. Make public static folder app.use(express.static(“public”));

// 3. Routes app.get(“/”, function(req, res) { res.send(“Hello from demo app!”); });

// 4. Start the server app.listen(PORT, function() { console.log(“Listening on port ” + PORT + “.”); }); `

You can follow along with the numerals in the comments as we describe the changes we’ve made: 1. First we initialized our Express app in a variable called app which we will use going forward to create routes, listen on ports, and more. 2. Next we setup a static folder called “/public” in our directory. We put assets in here like index.html or style.css and they can be directly accessed by going to “/index.html” or “/style.css” respectively.
3. Then we setup the home route “/” for our application as an example of how to setup a route in express. In this case our response to a request to the home route (“http://localhost/) will be “Hello from demo app!”. 4. Lastly but most importantly, we made our app start listening on port 3000 and we gave a log message to indicate that our app is successfully listening.

We can run our simple app and just verify it is listening:

$ node app.js
Listening on port 3000.
_

As you can see our simple app is now successfully listening on port 3000.

We can also go to ‘http://localhost:3000/’ and verify that we receive our “Hello from demo app!” response which we do:

Image from Gyazo

Creating a Schema using Mongoose

Now we’ll create a schema that will define the data that we want to store in our database. We’ll do this in a new file called product.js. Let’s take a look at the file and discuss the details afterwards.

File: /demo/model/Product.js `js var mongoose = require(“mongoose”);

// Get the Schema constructor var Schema = mongoose.Schema;

// Using Schema constructor, create a ProductSchema var ProductSchema = new Schema({ name: {


type: String,
required: true

}, quantity: {


type: Number,
required: true

}, departments: {


type: Array,
required: true

} });

// Create model from the schema var Product = mongoose.model(“Product”, ProductSchema);

// Export model module.exports = Product; `

Here you can see how you create a schema for your model. You need to require mongoose Then you use mongoose.Schema to create your schema We have an example of a simple schema which defines each field, it’s type, and whether it’s required or not. All the options available for your schema are beyond the scope of this article but there are numerous datatypes and options such as default value that are available in most database technologies. Our schema has three fields name, quantity, and departments which have String, Number, and Array datatypes respectively.

Create Our Post Route

Next we will create a route that a browser can send json to and create a Product. Here is where the Express framework shines and allows us to easily create a Post route. Let’s look at the code:

File: /demo/app.js `js // Route for creating a new Product app.post(“/product”, function(req, res) { console.log(“in post request”); Product.create(req.body)


.then(function(dbProduct) {
  // If we were able to successfully create a Product, send it back to the client
  res.json(dbProduct);
})
.catch(function(err) {
  // If an error occurred, send it to the client
  res.json(err);
});

}); ` We define a POST route to /product that takes in a request as JSON and if successful returns the JSON of that created product. The Mongoose function create() function on our model is called to create the data Product.create() and store it in the Mongo Database. As you can see all we need to give it is the request body and it will return a promise that will return if it completed successfully or not. If it completed successfully it will execute the code in the .then() block and if it failed it will execute the code in the .catch() block. If it succeeds the will return the JSON of the new product. If it fails it will return the error.

But before we can execute this POST we need to allow Mongoose to communicate to Mongo. We’ll set that up next in the app.js file.

Connecting Mongoose to MongoDB

To connect Mongoose to your instance of MongoDB is very simple. In your app.js file insert a line of code similar to this indicating to Mongoose where to find your database. We are calling our database grocerydb so our code looks like this:

mongoose.connect("mongodb://localhost/grocerydb", { useNewUrlParser: true });

The full app.js file should now look like:

var express = require("express");
var mongoose = require("mongoose");

// Require model
var Product = require("./models/Product.js");

// Connect to MongoDB
mongoose.connect("mongodb://localhost/grocerydb", { useNewUrlParser: true });

var PORT = 3000;

// Initialize Express
var app = express();

// Parse request body as JSON
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Make public static folder
app.use(express.static("public"));

// Routes
app.get("/", function(req, res) {
  res.send("Hello from demo app!");
});

// Route for creating a new Product
app.post("/product", function(req, res) {
  console.log("in post request");
  Product.create(req.body)
    .then(function(dbProduct) {
      // If we were able to successfully create a Product, send it back to the client
      res.json(dbProduct);
    })
    .catch(function(err) {
      // If an error occurred, send it to the client
      res.json(err);
    });
});

// Start the server
app.listen(PORT, function() {
  console.log("Listening on port " + PORT + ".");
});

Test Our Post Route

Now that we have Mongoose connected to our database we want to check if our Post route works. An easy way to test our route is to use Google’s Application Postman which is an easy to use application for testing API routes. In Postman we create a new request of type POST to the url http://localhost:3000/product, with Header Content-Type as application/json and in the body under the raw section we give it the JSON of the product that we want to create. For routes that require you to send data it’s typically best to use Postman.

Here is the JSON for one product we created:

{
    "name": "Soda",
    "quantity": 101,
    "departments": ["Beverages", "Checkout"]
}

Here is a couple screenshots showing how we setup the POST request from Postman:

Image from Gyazo Image from Gyazo

When we make a request to this route from Postman with the product JSON we get a result that looks like this:

{
    "departments": [
        "Beverages",
        "Checkout"
    ],
    "_id": "5cc70e1c896887120db2bd03",
    "name": "Soda",
    "quantity": 101,
    "__v": 0
}

As you can see it’s created a new Product in the Mongo database with an _id of 5cc70e1c896887120db2bd03 that has all the fields we’ve described. The __v field is a version number that we don’t need to be concerned with right now.

Add a Get Route

The final thing we will do to is create a route that gets all the Products in the database. Here’s how we create that route in app.js using express:

File: /demo/app.js

app.get("/products", function(req,res) {
  Product.find({})
  .then(function(dbProducts) {
    res.json(dbProducts);
  })
  .catch(function(err) {
    res.json(err);
  })
});

We can either use Postman or the browser to test this new route at http://localhost:3000/products. This request doesn’t require sending any data so we’ll just use the browser although you can use either.

Here’s what was returned:

Image from Gyazo

As you can see it returned all of the Products that we’ve created so far.

So know we have a backend that both can create and retrieve entities based on a custom model that you created. This is the basis for an web application using Mongoose and MongoDB.

Conclusion

Finally we have a basic app with a backend written in Javascript that can communicate with MongoDB through Mongoose. You can make requests to the server from a browser and the server will interact with the database and return results. Although we haven’t fleshed out the user interface we have concentrated on the building blocks of an application that connects NodeJS with MongoDB using the Mongoose library from npm. If you wanted to start expanding this application you would add more routes for creating documents, deleting documents, updating documents, and so on. Of course you’d also flesh out the front-end but this article was more focused on showing you the basic building blocks. We hope you found this information helpful and don’t hesitate to reach out with any questions or suggestions.

Just The Code

If you’re already comfortable with the concepts and technology mentioned in this article, here’s all the code we used for this demonstration:

File /demo/app.js

var express = require("express");
var mongoose = require("mongoose");

// Require model
var Product = require("./models/Product.js");

// Connect to MongoDB
mongoose.connect("mongodb://localhost/grocerydb", { useNewUrlParser: true });

var PORT = 3000;

// Initialize Express
var app = express();

// Parse request body as JSON
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Make public static folder
app.use(express.static("public"));

// Routes
app.get("/", function(req, res) {
  res.send("Hello from demo app!");
});

app.get("/products", function(req,res) {
  Product.find({})
  .then(function(dbProducts) {
    res.json(dbProducts);
  })
  .catch(function(err) {
    res.json(err);
  })
});

// Route for creating a new Product
app.post("/product", function(req, res) {
  ß  Product.create(req.body)
    .then(function(dbProduct) {
      // If we were able to successfully create a Product, send it back to the client
      res.json(dbProduct);
    })
    .catch(function(err) {
      // If an error occurred, send it to the client
      res.json(err);
    });
});

// Start the server
app.listen(PORT, function() {
  console.log("Listening on port " + PORT + ".");
});

File: /models/Product.js

var mongoose = require("mongoose");

// Get the Schema constructor
var Schema = mongoose.Schema;

// Using Schema constructor, create a ProductSchema
var ProductSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  quantity: {
    type: Number,
    required: true
  },
  departments: {
    type: Array,
    required: true
  }
});

// Create model from the schema
var Product = mongoose.model("Product", ProductSchema);

// Export model
module.exports = Product;

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.