build a rest api with node.js express js and mongodb tutorial code example
Example 1: 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' }); });};
Example 2: fetch api based on id nodejs and mongodb
// contactModel.jsvar mongoose = require('mongoose');// Setup schemavar contactSchema = mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true }, gender: String, phone: String, create_date: { type: Date, default: Date.now }});// Export Contact modelvar Contact = module.exports = mongoose.model('contact', contactSchema);module.exports.get = function (callback, limit) { Contact.find(callback).limit(limit);}