Easily Add Mongo CRUD APIs to any NodeJS Express project

March 29, 2017
by Rahil Shaikh
  • Express Mongo CRUD

We have already seen in some of our previous videos and tutorials how we can build CRUD REST APIs with NodeJS, Express, and Mongoose. REST based CRUD APIs are the minimum that an application exposes for any MongoDB document or say mongoose model.

So, writing separate APIs for each model every time is a waste of effort and time. And trust me doing repetitive mundane work is annoying.

In this tutorial, I will show you how you can instantly add REST based CRUD APIs to any of your Node.js Express project. For this, we will use an npm module express-mongo-crud which I built recently.

Words model, schema and document have been used interchangeably through this article. They mean the same.

Motivation Behind express-mongo-crud

Lately, I’ve been working with projects involving MongoDB as the core database and while doing so I came to the realization that each model required exposing CRUD as a minimum set of APIs. Of course, during the course of the development, we end up doing a lot more than just CRUD, but this was the minimum in almost each case. So I decided why not just create a middleware that does this job for us and we can only focus on creating schemas/models.

express-mongo-crud

express-mongo-crud is an npm package which can be used as an express middleware. It reads models from a specific directory and exposes CRUD APIs for each model. So all you have to do is write a model in mongoose syntax and include the middleware, that’s it.
There are a lot of advantages of using this middleware, bellow are few of them.

  1. Very Easy to Use
  2. Works with existing APIs, you can also add APIs on top of it.
  3. Supports almost all the queries required wile listing objects.
  4. Provides Swagger Suite along with tagging per model.
  5. Can be used in your existing Application or used to create a standalone service that exposes CRUD APIs only

So let us go ahead and build a node server which will use our middleware to expose REST APIs for our model.

Application

So to demonstrate this I’ll first build a simple express application and then include this middleware to show it’s power.

Let’s start with a new node project. Create a project directory and run npm init --yes. Next let’s have a look at our package.json

package.json

{
  "name": "store-app",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "mongoose": "^4.9.1"
  }
}

Run npm install to install all the dependencies.

Now let’s create a basic express app with a single api. We are doing this to see how we would be able to add crud apis later on without affecting our existing application.

app.js

var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var PORT = 3000;
mongoose.connect('localhost:27017/mongocrud');
 
app.use(bodyParser.json()); // add body parser

router.get('/myapi', function(req, res){
    res.send('works well');
});

app.use(router);
 
app.listen(PORT, ()=>{
    console.log('started at '+PORT);
})

Run the application by hitting node app.js. Once the application is started whe you hit the url http://localhost:3000/myapi you would see works well printed on the browser.

Please note that you must have MongoDB running on the default port which is 27107.

Now that we have our basic app running, let’s use Express Mongo CRUD middleware to make it more ambitious.

Using express-mongo-crud

Let’s first go ahead and add a model.

Create a directory named /models in your application root along side app.js. This is because the middleware we are using looks for mongoose models in that specific directory.

Let’s go ahead and add a model or two. A model file should be named as <modelname>.model.js. A model uses mongoose syntax.

/models/product.model.js

module.exports = function(mongoose){
    return [{
        name: {type: String, required: true},
        description: {type: String},
        rating: {type: String},
        type: {type: String},
        colors: [String]
    }, {
        timestamps: true,
        strict: false
    }]
};

 
Now let’s install our middleware.

npm i express-mongo-crud --save

This will install express-mongo-crud and save it to dependencies.

Now open up app.js. Well will require our middleware and use it in our app. Our app.js will look like this.

app.js

var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var instantMongoCrud = require('express-mongo-crud');
var PORT = 3000;
 
 
 
mongoose.connect('localhost:27017/mongocrud');
 
app.use(bodyParser.json()); // add body parser (required)
var options = { //specify options
    host: `localhost:${PORT}`
}
app.use(instantMongoCrud(options)); // INCLUDE OUR MIDDLEWARE

router.get('/myapi', function(req, res){
    res.send('works well');
});

app.use(router);
 
app.listen(PORT, ()=>{
    console.log('started at '+PORT);
})

Note. We need to make sure we have used app.use(bodyParser.json()) and mongoose.connect() before requiring the middleware. express-mongo-crud also takes a few options.

Before running the app I’ll just go ahead and add one more model to our application.

/models/article.model.js

module.exports = function(mongoose){
    return [{
        name: {type: String, required: true},
        description: {type: String},
                author: {
                    name: {type: String},
                    website: {type: String}
                }
    }, {
        timestamps: true
    }]
};

 

Run the application by hitting node app.js.

Express Mongo CRUD

Express Mongo CRUD

Once the app runs, navigate to http://localhost:3000/apidoc you should see a swagger suite, where you can try out the exposed APIs.

Express Mongo CRUD

Swagger Suite

Express Mongo CRUD

Add Data

List data

List data

And that’s it. Now we can add as many models we want and we will have CRUD apis exposed for each of them.

Invitation to contribute

express-mongo-crud is quite a useful package that can save a lot of time and repeated efforts for developers building apps with Node.js and MongoDB. I have built in the basic and most required features into it, but there is a room for new features and improvements. If you are interested in contributing to the project go ahead and make a pull request and I’ll review it and merge. If you provide a few good pull-requests, depending on your interests I’ll be happy to give you direct push access to the repository.

Conclusion

Here we saw how we can easily add Mongo CRUD APIs to any Node.js and ExpressJS project by using our express-mongo-crud middleware. express-mongo-crud is an npm package to create and expose CRUD APIs in Node.js ExpressJS projects for mongoose models. It also automatically creates swagger documentation for each API.

Further Links

  1. express-mongo-crud
  2. Full Stack web development course

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

Leave a Comment