Creating a CRUD app using Node.js, Express.js and MongoDB

Introduction

Getting Started

node -v
mongo --version

Let’s build the App

npm init
npm install --save express body-parser mongoose
const express = require('express')//Initialize express app
const app = express();
//Initialize the sever
app.listen(3000, () => {
console.log('sever listening on port:3000');
});
node index.js
const mongoose = require('mongoose')
// Connecting to DBmongoose.connect('mongodb://localhost:27017/AddressBook', {useNewUrlParser: true, useUnifiedTopology: true
}).then(() => {
console.log('connected to db')
}).catch((error) => {
console.log(error)
})
const mongoose = require('mongoose');
// Schema for AddressBook
const addressSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
phone: {
type: Number,
required: true
},
place: {
type: String,
required: true
}
})
//Creating the collection Address
const Address = mongoose.model('Address', addressSchema)
module.exports = Address;
app.METHOD(PATH, HANDLER)
const Address = require('./model/models')
const bodyParser = require('body-parser')// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
npm install -g --save-dev nodemon
nodemon index.js
// Adding a User to AddressBookapp.post('/', (req, res) => {
name = req.body.name,
email = req.body.email,
phone = req.body.phone,
place = req.body.place
let newAddress = new Address({
name: name,
email: email,
phone: phone,
place: place
})
newAddress.save().then((address) => {
res.send(address)
}).catch((err) => {
console.log(error)
})
})
mongodb://localhost:27017
// Reading a Uder from AddressBookapp.get('/:id', (req, res) =>{
Address.findById(req.params.id, (err, user) =>{
res.send(user)
})
})
// Updating the Userapp.post('/update/:id', (req, res) => {
let address = {}
if (req.body.name) address.name = req.body.name
if (req.body.email) address.email = req.body.email
if (req.body.phone) address.phone = req.body.phone
if (req.body.place) address.place = req.body.place
address = { $set: address }Address.update({_id: req.params.id}, address).then(() => {
res.send(address)
}).catch((err) => {
console.log(error)
})
})
// Deleting the User from AddressBookapp.delete('/delete/:id', (req, res) => {
Address.remove(_id: req.params.id).then(() => {
res.send('user deleted')
}).catch((err) => {
console.log(error)
})
})

Wrapping up

Node.js | Golang | Developer | amljs.me