Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

crud-restapis-with-nodejs-express-mongodb-feature-image

In the tutorial, we show how to build CRUD RestAPIs with NodeJS/Express and MongoDB using Mongoose.

Related posts:
NodeJs/Express RestAPIs – POST/GET/PUT/DELETE requests
NodeJs/Express MongoDB One-to-Many related models

Goal

Prerequisites: Create NodeJs/RestAPIs tutorial

-> Project structure:

/nodejs-restapi
	/app
		/controllers
			customer.controller.js
		/routes
			customer.routes.js
	/node-modules
	package.json
	server.js

Objective: design, create models and interact with MongoDB by Mongoose.

-> The tutorial will create a project as below structure:

/nodejs-restapi-mongodb
	/app
		/config
			mongodb.config.js
		/controllers
			customer.controller.js
		/models
			customer.model.js
		/routes
			customer.routes.js
	/node_modules
	package.json
	server.js

Mongoose

Mongoose is a MongoDB object modeling tool that provides a schema-based solution to model data. Mongoose is installed in your project (package.json) by commandline:

npm install mongoose
"dependencies": {
	...
	
	"mongoose": "^5.0.13",
	
	...
}

How to define a Mongoose’s schema for JavaScript object and connect with MongoDB?

Customer Object:

var customer = {
				firstname: "Jack",
				lastname: "Davis",
				age: 25 // 18 <= age <= 65
			}

-> Mongoose's schema, connect & save document to MongoDB:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/nodejs-demo');

const CustomerSchema = mongoose.Schema({
    firstname: String,
    lastname: String,
	age: { type: Number, min: 18, max: 65, required: true }
});

const customer = new Customer({ firstname: "Jack",
								lastname: "Davis",
								age: 25 });
								
customer.save().then(() => console.log('Save Ok!'));

Practice

Create NodeJs/Express project

Following the guide to create a NodeJS/Express project.

Install Express/Body-parse/Mongoose by commandline:

npm install express body-parser mongoose --save

-> 'package.json' :

{
  "name": "nodejs-restapi-mongo",
  "version": "1.0.0",
  "description": "NodeJs-RestApis",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJs-RestAPIs"
  ],
  "author": "JSA",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3",
    "mongoose": "^5.0.13",
    "npm": "^5.8.0"
  }
}

Mongoose interact with MongoDB
Mongoose Schema
const mongoose = require('mongoose');

const CustomerSchema = mongoose.Schema({
    firstname: String,
    lastname: String,
	age: { type: Number, min: 18, max: 65, required: true }
});

module.exports = mongoose.model('Customer', CustomerSchema);
Configure MongoDB's URL

In the root folder, create a file 'app/config/mongodb.config.js' as below content:

module.exports = {
    url: 'mongodb://localhost:27017/nodejs-demo'
}
Connect to MongoDB

In the 'server.js' file , configure mongodb connection:

...

// Configuring the database
const dbConfig = require('./app/config/mongodb.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
    console.log("Successfully connected to MongoDB.");    
}).catch(err => {
    console.log('Could not connect to MongoDB.');
    process.exit();
});

...

Full 'server.js' file:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())

// Configuring the database
const dbConfig = require('./app/config/mongodb.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
    console.log("Successfully connected to MongoDB.");    
}).catch(err => {
    console.log('Could not connect to MongoDB.');
    process.exit();
});

require('./app/routes/customer.routes.js')(app);

// Create a Server
var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("App listening at http://%s:%s", host, port)

})
Implement CRUD APIs
Routes

In the root folder, create a file 'app/routes/customer.routes.js' as below content:

module.exports = function(app) {

    var customers = require('../controllers/customer.controller.js');

    // Create a new Customer
    app.post('/api/customers', customers.create);

    // Retrieve all Customer
    app.get('/api/customers', customers.findAll);

    // Retrieve a single Customer by Id
    app.get('/api/customers/:customerId', customers.findOne);

    // Update a Customer with Id
    app.put('/api/customers/:customerId', customers.update);

    // Delete a Customer with Id
    app.delete('/api/customers/:customerId', customers.delete);
}
Controllers

In root folder ‘nodejs-restapi’, create a controller folder ‘/app/controllers’. Then create a file ‘/app/controllers/customer.controller.js’ that contains methods for executing above URL requests:

const Customer = require('../models/customer.model.js');


// POST a Customer
exports.create = (req, res) => {
    // Create a Customer
    const customer = new Customer({
        firstname: req.body.firstname,
		lastname: req.body.lastname,
        age: req.body.age
    });

    // Save a Customer in the MongoDB
    customer.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message
        });
    });
};


// FETCH all Customers
exports.findAll = (req, res) => {
    Customer.find()
    .then(customers => {
        res.send(customers);
    }).catch(err => {
        res.status(500).send({
            message: err.message
        });
    });
};


// FIND a Customer
exports.findOne = (req, res) => {
    Customer.findById(req.params.customerId)
    .then(customer => {
        if(!customer) {
            return res.status(404).send({
                message: "Customer not found with id " + req.params.customerId
            });            
        }
        res.send(customer);
    }).catch(err => {
        if(err.kind === 'ObjectId') {
            return res.status(404).send({
                message: "Customer not found with id " + req.params.customerId
            });                
        }
        return res.status(500).send({
            message: "Error retrieving Customer with id " + req.params.customerId
        });
    });
};

// UPDATE a Customer
exports.update = (req, res) => {
    // Find customer and update it
    Customer.findByIdAndUpdate(req.params.customerId, {
        firstname: req.body.firstname,
		lastname: req.body.lastname,
		age: req.body.age
    }, {new: true})
    .then(customer => {
        if(!customer) {
            return res.status(404).send({
                message: "Customer not found with id " + req.params.customerId
            });
        }
        res.send(customer);
    }).catch(err => {
        if(err.kind === 'ObjectId') {
            return res.status(404).send({
                message: "Customer not found with id " + req.params.customerId
            });                
        }
        return res.status(500).send({
            message: "Error updating customer with id " + req.params.customerId
        });
    });
};

// DELETE a Customer
exports.delete = (req, res) => {
    Customer.findByIdAndRemove(req.params.customerId)
    .then(customer => {
        if(!customer) {
            return res.status(404).send({
                message: "Customer not found with id " + req.params.customerId
            });
        }
        res.send({message: "Customer deleted successfully!"});
    }).catch(err => {
        if(err.kind === 'ObjectId' || err.name === 'NotFound') {
            return res.status(404).send({
                message: "Customer not found with id " + req.params.customerId
            });                
        }
        return res.status(500).send({
            message: "Could not delete customer with id " + req.params.customerId
        });
    });
};
Run & Check results

Run the NodeJs/Express project:

nodejs-restapi-mongodb>node server.js
App listening at http://:::8081
Successfully connected to MongoDB.

Use Postman to check result ->

- POST a customer:

nodejs-mongodb-create document

nodejs-mongodb-restapi-validation error model

– GET all customers:

nodejs-mongodb-fetch all documents

– GET a customer by id:

nodejs-mongodb-get a document

– PUT a customer:

nodejs-mongodb-put a document

– DELETE a customer:

nodejs-mongodb-restapi-delete a document

nodejs-mongodb-fetch all customers

Sourcecode

NodeJs-RestApi-MongoDB



By grokonez | April 8, 2018.

Last updated on February 6, 2020.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*