In this tutorial, you will learn how to create restful CRUD APIs using node.js express and MongoDB with mongoose.
Node.js Express and MongoDB Build a Crud Rest API Example
Here are steps:
Step 1 – Create Node Express js App
Run the following command on cmd to create the node js app:
mkdir my-app cd my-app npm init -y
Step 2 – Install express flash Validator ejs body-parser mongoose Modules
Run the following command on the cmd to express flash ejs body-parser mysql dependencies :
npm install -g express-generator
npx express --view=ejs
npm install
npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install cors --save
npm install mongoose
Step 3 – Connect App to MongoDB
Create a database.js
file in application root directory, and add the following code to it:
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true}); var conn = mongoose.connection; conn.on('connected', function() { console.log('database is connected successfully'); }); conn.on('disconnected',function(){ console.log('database is disconnected successfully'); }) conn.on('error', console.error.bind(console, 'connection error:')); module.exports = conn;
Step 4 – Create Model
Create Models
directory, and in this directory create userModel.js
file:
var db = require("../database"); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var BookSchema = new Schema({ title: String, author: String, category: String }); module.exports = mongoose.model('Book', BookSchema);
Step 5 – Create CRUD Apis Routes
Edit routes/users.js
route file, and create CRUD(Create, Read, Update, Delete) restful api routes in it:
var express = require('express'); var Book = require('../models/book'); var router = express.Router(); router.get('/', function(req, res){ console.log('getting all books'); Book.find({}).exec(function(err, books){ if(err) { res.send('error has occured'); } else { console.log(books); res.json(books); } }); }); router.get('/:id', function(req, res){ console.log('getting one book'); Book.findOne({ _id: req.params.id }).exec(function(err, book){ if(err) { res.send('error has occured'); } else { console.log(book); res.json(book); } }); }); router.post('/', function(req, res){ var newBook = new Book(); newBook.title = req.body.title; newBook.author = req.body.author; newBook.category = req.body.category; newBook.save(function(err, book){ if(err) { res.send('error saving book'); } else { console.log(book); res.send(book); } }); }); router.put('/:id', function(req, res){ Book.findOneAndUpdate({ _id: req.params.id },{ $set: { title: req.body.title, author: req.body.author, category: req.body.category } },{ upsert: true },function(err, newBook){ if(err) { res.send('error updating book'); } else { console.log(newBook); res.send(newBook); } }); }); router.delete('/:id', function(req, res){ Book.findByIdAndRemove({ _id: req.params.id },function(err, book){ if(err) { res.send('error deleting book'); } else { console.log(book); res.send(book); } }); }); module.exports = router;
Step 5 – Import Modules in App.js
Import express flash session body-parser mongoose dependencies in app.js; as shown below:
const createError = require('http-errors'); const express = require('express'); const path = require('path'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const bodyParser = require('body-parser'); const cors = require('cors'); const books = require('./routes/books'); const app = express(); app.use(express.json()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(cors()); app.use('/books', books); // Handling Errors app.use((err, req, res, next) => { // console.log(err); err.statusCode = err.statusCode || 500; err.message = err.message || "Internal Server Error"; res.status(err.statusCode).json({ message: err.message, }); }); app.listen(3000,() => console.log('Server is running on port 3000'));
Step 7 – Test CRUD REST API Application
You can use the following command to start node js app server:
//run the below command
npm start
Open browser and type the following URL:
http://127.0.0.1:3000/books
Conclusion
Build restful crud api with node.js express and mongodb; In this tutorial; you have learned how to build/create a crud rest api using node.js express and mongodb with mongoose.
Brilliant article! I don’t see such articles any more these days. Well thought out and really well written. Couldn’t agree any further. Thank you for this.