opencodez

Simple CRUD application using Node.js and Mongoose

In this article, we are going to develop a Simple CRUD application using Node.js and Mongoose.

Software used

Mongoose

Mongoose provides a simple and straight-forward, schema-based solution to model your application data. It has support for built-in type casting, validation, query building, business logic hooks and more. The Mongoose helps to reduce the boilerplate code that we may have to write for MongoDB.

Handlebars

When we start to develop our web application, we usually try to keep the business logic and HTML views separate. We may even want to have some common templates that we can reuse at different places. Handlebars is such one template engine which let you build semantic templates effectively with ease

We will develop an end to end web application with Node.js as our backend and Bootstrap and Jquery as frontend.

NPM Packages

After you init your project directory with npm init install below packages.

npm install --save express
npm install --save express-handlebars
npm install --save mongoose
npm install --save babel-cli babel-core babel-preset-env body-parser cors nodemon

The babel and other packages are installed for ease of development. Below is our directory structure.

Configure Handlebars

For Handlebars, we need to let it know what are our layout and views folder and files. Below we are configuring the main layout and file extension we are going to use.

import handlebars from "express-handlebars";

const path = __dirname + '/../views/';

const hb = handlebars({
            defaultLayout:"main",
            extname:"hbs",
            layoutsDir:path + "layouts",
            partialsDir:path + "common"
        });

module.exports = hb;

After this, the exported handlebar object can be used in our express app-

const app = express();

//set template engine
app.engine("hbs", hb);
app.set("view engine","hbs");

For handlebars, we also have to define the layouts/main.hbs x

{{x header }}
    {{{body}}}
{{x footer }}

Configure Mongoose

For our example, we are connecting to MongoDB on a cloud using free plan available at MongoDB Atlas.

Make sure you create your account there and set up some security like user/password, whitelisted IP address etc.

import mongoose from "mongoose";

mongoose.connect(
  "mongodb+srv://xyour userx:xyour passwordx@opencodez-pzgjy.gcp.mongodb.net/test?retryWrites=true",
    { 
      useNewUrlParser: true
    }
  );

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
  console.log("Connected to MongoDB database")
});

module.exports = db;

In the above code, you need to replace the user and password as per your environment. This will connect to the cloud MongoDB and create a test database.

The mongoose models use the available connection in your application. So you have to just import it into your app.

import db from "./config/database";

Define Schema and Model

A Schema is the core element in Mongoose. Each schema is mapped to MongoDB collection and defines its structure. To create a Model we need to provide the schema and name we need to use across our application.

In our example, we will define a simple User schema, with inbuilt id and some fields.

import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: String,
    address: String,
    salary : Number
});

var UserModel = mongoose.model("User", userSchema);

module.exports = UserModel;

The code above defines a schema and a model named User

Routes

Now we will define routes to list our user, add a user and delete users. Our application will look like this

You can read here about Build a RESTful API using Node.js

Add User

To add the user, we will accept a couple of fields from our application form. It will be passed as JSON data to our endpoint. We will use ID as an internally generated key.

router.post("/add", (req, res, next) =x {

    const user = new User({
        _id: mongoose.Types.ObjectId(),
        name: req.body.name,
        address:req.body.address,
        salary: req.body.salary
    });

    user.save()
    .then(result =x {
        res.status(200).json({
            docs:[user]
        });
    })
    .catch(err =x {
        console.log(err);
    });
});

If user is successfully saved, we will pass it back to our frontend for display.

Delete User

Before we delete and document from MongoDB, we need to find it first. In below code, we will find the User with given ID and if found we will remove it.

router.post("/delete", (req, res, next) =x {
    const rid = req.body.id;

    User.findById(rid)
        .exec()
        .then(docs =x {
            docs.remove();
            res.status(200).json({
                deleted:true
            });
        })
        .catch(err =x {
            console.log(err)
        });
});

List Users

Whenever a new user is created or updated, we need to list it on our UI. On page load, it will simply query the MongoDB and find all Users.

router.get("/list", (req, res, next) =x {
    User.find({})
        .exec()
        .then(docs =x {
            res.status(200).json({
                docs
            });
        })
        .catch(err =x {
            console.log(err)
        });
});

You can find the real data stored on our cloud MongoDB instance-

Jquery Support

As mentioned earlier we are using Jquery to ease our frontend development. Below is a sample on how we are retrieving the listing for all user-

$.ajax({
	url: "users/list",
	dataType: "json",
})
.done((data) =x {
	if(data) {
		var odata = $.parseJSON(JSON.stringify(data.docs));
		odata.forEach(item =x {
			$('#myTable x tbody:last-child').append(getRowHtml(item));
		});
	}
})
.fail((err) =x {
	console.log("Error");
});

You can find more code and utility functions in home.js

Running the Application

To run the application, open a command prompt and navigate to project directory. Run command as

npm start

If you are running for the first time, then before you run the start command, initialize the project with

npm init

This will start the node server at port 6002 and you can access the application at url http://localhost:6002/

Conclusion

In this article, we have seen how we can develop a simple CRUD application using Node.js and Mongoose.

You can download the complete code from our GIT Repo

Download Code