node js api with mongodb 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: rest api with mongodb and nodejs

npm install express --save

Example 3: fetch api based on id nodejs and mongodb

// Import expresslet express = require('express');// Import Body parserlet bodyParser = require('body-parser');// Import Mongooselet mongoose = require('mongoose');// Initialise the applet app = express();// Import routeslet apiRoutes = require("./api-routes");// Configure bodyparser to handle post requestsapp.use(bodyParser.urlencoded({    extended: true}));app.use(bodyParser.json());// Connect to Mongoose and set connection variablemongoose.connect('mongodb://localhost/resthub', { useNewUrlParser: true});var db = mongoose.connection;// Added check for DB connectionif(!db)    console.log("Error connecting db")else    console.log("Db connected successfully")// Setup server portvar port = process.env.PORT || 8080;// Send message for default URLapp.get('/', (req, res) => res.send('Hello World with Express'));// Use Api routes in the Appapp.use('/api', apiRoutes);// Launch app to listen to specified portapp.listen(port, function () {    console.log("Running RestHub on port " + port);});

Tags:

Java Example