Creating a CRUD app with Node.js and MongoDB

NSerus
4 min readApr 5, 2021

Hello peppos!!

Today we are going to make a CRUD app using the mongoDB database (i made a tutorial on installing on manjaro here) and using Node.js (install tutorial here, also on manjaro).

>>>>>ALSO, USE POSTMAN<<<<<

Building the Environment…

After creating the folder that will host the project, we initiate the project with:

npm init

Also, we will need the following packages:

  • Express.js — Framework that allows developing of web apps in a simple way.
  • body-parser — Used to manipulate JSON files
  • mongoose — Database that supports the project

Install the needed packages with:

npm install --save express body-parser mongoose

Create the index.js file and implement this code the make a server:

// dependenciesconst mongoose = require('mongoose');
const app = require('express')(); // the () inits express
let bodyParser = require('body-parser');
//Indicate the port to associate to the server, in this case 8000
var port = process.env.PORT || 8000;
app.listen(port, ()=>{console.log("Server UP");});

Executing the server with:

node index.js

It should give a blank page on Postman.

Using MVC…

After being able to make the server run, we can start customizing the way we intended.

First, for organizational purposes, we are going to make 3 directories:

  • Models — For the Database/Back-End stuff.
  • View —For the Visual/Front-End stuff.
  • Controller — For controlling the transactions between the View and the Model.

This it the MVC and it’s wildly used on the industry and it will be the model that i will use for every of my Node.js tutorials.

We will also create the directory routes, to store the routes for the paths that we will use

The Model

The model of the app should be inside the models folder, i called it model.js and write in it the following code:

var mongoose = require('mongoose');  //using mongoose//the schema of the model, aka the structure
var SmartphoneSchema = mongoose.Schema({
name: {
type: String,
required: true
},
cellphone: {
type: String,
required: true
}
});
// Export Smartphone Model
var Smartphone = module.exports = mongoose.model('smartphone', SmartphoneSchema);
module.exports.get = function (callback, limit) {
Smartphone.find(callback).limit(limit);
}

The Routes

The routes should be on the routes folder, i called it routes.js and it has the following code:

const router = require('express').Router(); //router function of //express
const controller = require('../controllers/controller');
//API HOME
router.get('/', (req, res)=>
{
res.send('API WORKING');
});
// Smartphone routes
router.route('/smartphone').get(controller.index)
.post(controller.add);
router.route('/smartphone/:id').get(controller.view)
.patch(controller.update)
.put(controller.update)
.delete(controller.delete);
module.exports = router;

The Controller

Same thing for the controller, create on the controllers directory:

//Import Smartphone Model
Smart = require('../models/model');
//Index
exports.index = (req, res)=>
{
Smart.get((err, smart)=>
{
if (err)
{
res.json({
status: "error",
message: err
});
}
res.json({
status: "OK",
message: "Successfully got Smartphones",
data: smart
});
});
};
//New Smartphone
exports.add = (req, res)=>
{
var smart = new Smart();
smart.name = req.body.name? req.body.name: smart.name;
smart.cellphone = req.body.cellphone;
//Saving and error checking
smart.save((err)=>
{
if (err) res.json(err);
res.json({
message: "New Smartphone Added!",
data: smart
});
});
};
//Get Smartphone
exports.view = (req, res)=>
{
Smart.findById(req.params.id, (err, smart)=>
{
if (err) res.send(err);
res.json({
message: 'Smartphone Details',
data: smart
});
});
};
//Update Smartphone
exports.update = (req, res)=>
{
Smart.findById(req.params.id, (err, smart)=>
{
if (err) res.send(err);
smart.name = req.body.name ? req.body.name : smart.name;
smart.cellphone = req.body.cellphone;
//Saving and checking errors
smart.save((err)=>
{
if (err) res.json(err)
try
{
res.json({
message: "Smartphone Updated Successfully",
data: smart
});
}
catch (e)
{
console.log('There was an error and it couldnt send anymore headers',e)
}
});
});
};
//Delete Smartphone
exports.delete = (req, res)=>
{
Smart.deleteOne({_id: req.params.id}, (err, contact)=>
{
if (err) res.send(err)
try
{
res.json({
status: "OK",
message: 'Smartphone Deleted!'
});
}
catch (e)
{
console.log('There was an error and it couldnt send anymore headers',e)
}
});
};

Finishing up…

Adding Routes to the Index

We need to implement the routes module on the index with:

const apiRoutes = require(“./routes/routes”);

Body-Parser

For parsing the JSON code we need the following code:

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/', apiRoutes)

Local DataBase

We are going to automatically create a local MongoDB using mongoose, just add this code to the index:

//Connect to DB
const dbPath = 'mongodb://localhost/SmartApp';
const options = {useNewUrlParser: true, useUnifiedTopology: true}
const mongo = mongoose.connect(dbPath, options).then(console.log('Connected')).catch(e=>console.log(e));
var db=mongoose.connection;

Summing all these changes, the final code should look like this

let bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = require('express')();
const apiRoutes = require("./routes/routes");app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Connect to DB
const dbPath = 'mongodb://localhost/SmartApp';
const options = {useNewUrlParser: true, useUnifiedTopology: true}
const mongo = mongoose.connect(dbPath, options).then(console.log('Connected')).catch(e=>console.log(e));
var db=mongoose.connection;//Set / to the routes file
app.use('/', apiRoutes)
var port = process.env.PORT || 8000;
app.listen(port, ()=>{console.log("Server UP");});

Testing with Postman

--

--