restful api with node js and mongodb code example
Example 1: rest api with mongodb and nodejs
npm install express --save
Example 2: fetch api based on id nodejs and mongodb
// contactController.js// Import contact modelContact = require('./contactModel');// Handle index actionsexports.index = function (req, res) { Contact.get(function (err, contacts) { if (err) { res.json({ status: "error", message: err, }); } res.json({ status: "success", message: "Contacts retrieved successfully", data: contacts }); });};// Handle create contact actionsexports.new = function (req, res) { var contact = new Contact(); contact.name = req.body.name ? req.body.name : contact.name; contact.gender = req.body.gender; contact.email = req.body.email; contact.phone = req.body.phone;// save the contact and check for errors contact.save(function (err) { // if (err) // res.json(err);res.json({ message: 'New contact created!', data: contact }); });};// Handle view contact infoexports.view = function (req, res) { Contact.findById(req.params.contact_id, function (err, contact) { if (err) res.send(err); res.json({ message: 'Contact details loading..', data: contact }); });};// Handle update contact infoexports.update = function (req, res) {Contact.findById(req.params.contact_id, function (err, contact) { if (err) res.send(err);contact.name = req.body.name ? req.body.name : contact.name; contact.gender = req.body.gender; contact.email = req.body.email; contact.phone = req.body.phone;// save the contact and check for errors contact.save(function (err) { if (err) res.json(err); res.json({ message: 'Contact Info updated', data: contact }); }); });};// Handle delete contactexports.delete = function (req, res) { Contact.remove({ _id: req.params.contact_id }, function (err, contact) { if (err) res.send(err);res.json({ status: "success", message: 'Contact deleted' }); });};