We are going to make web APIs using Express.js and will connect them to Mongo database. As you are aware, Mongo DB is a no-SQL type database and nowadays used very popularly. There are a lot of companies building services on top of it.
We will be creating a simple to-do web API in Express.js, so we will be supporting basic adding, retrieving, updating and deleting to-dos. We will be testing our web API using Postman.
This entire tutorial is available on github link
here
Software needed
- Node JS - Platform
- Mongo DB- database provider
- Postman – used for creating HTTP requests like GET, PUT, POST, DELETE
- Sublime/Notepad++ - IDE for writing code.
Before getting started, you have to install the software mentioned above according to your platform ( Win/ Mac/ Lin).
- Installing dependencies
You need to install the following packages in your node.js project. Mongoose will help in connecting and executing queries on Mongo DB. Morgan will help you log every event to the console so that we can check for the error.
- npm install body-parser
- npm install express
- npm install mongoose
- npm install morgan
After you have finished Mongo installation, you can start Mongo DB to listen to your node application.
Go to command prompt and then change the current directory to MongoDB\Server\3.2\bin where you will find mongod.exe. For Windows, it will be inside “program files”.
- C:\Program Files\MongoDB\Server\3.2\bin mongod --dbpath=c:\mongo
You need to mention file path after dbpath where you want to mongo to store db files. As soon as you run last query, your server will start listening to external ports.
-
Coding up
First, we will set up express, morgan, and body-parser. We will be using them later on.
- var express = require('express');
- var logger = require('morgan');
- var bodyParser = require('body-parser');
- var app = express();
- app.use(logger('dev'));
- app.use(bodyParser.json());
We need to connect to Mongo DB and the below statement will connect your application to Mongo where mongotest is the database name. Do not worry, if the mentioned database does not exist, it will automatically create for you.
- var mongoose = require('mongoose');
- mongoose.connect('mongodb://localhost:27017/mongotest');
Now, we will create a simple Todo schema with the fields Name and Content.
- var Schema = mongoose.Schema;
-
- var todosShema = new Schema({
- name: {
- type: String,
- required: true
- },
- content: {
- type: String
- }
- });
-
- var Todos = mongoose.model('todos', todosShema);
We will add routes for fetching all todos.
- app.get('/todos', function(req, res) {
- Todos.find({}, function(err, todos) {
-
- if (!todos) {
- res.statusCode = 404;
-
- return res.json({
- error: 'Not found'
- });
- };
-
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
-
-
- return res.json({
- error: 'Server error'
- });
- };
- });
- });
Let's add route for fetching one todo by id.
- app.get('/todo/:id', function(req, res) {
- Todos.findOne({
- "id": req.param.id
- }, function(err, todos) {
-
- if (!todos) {
- res.statusCode = 404;
- return res.json({
- error: 'Not found'
- });
- };
-
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
-
-
- return res.json({
- error: 'Server error'
- });
- };
- });
- });
- app.post('/todo', function(req, res) {
-
- var tdos = new Todos({
- name: req.body.name,
- content: req.body.content
- });
-
- tdos.save(function(err, todos) {
- console.log(err);
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- res.json({
- error: 'Server error'
- });
- }
- });
- });
- app.put('/todo/:id', function(req, res) {
-
- var tdos = {
- name: req.body.name,
- content: req.body.content
- };
-
- Todos.findOneAndUpdate({
- "id": req.param.id
- },tdos,function(err, todos) {
- console.log(err);
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- res.json({
- error: 'Server error'
- });
- }
- });
- });
- app.delete('/todo/:id', function(req, res) {
-
- Todos.findOneAndRemove({
- id: req.param.id
- },function(err, todos) {
- console.log(err);
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- res.json({
- error: 'Server error'
- });
- }
- });
- });
Finishing up.
- app.use(function(req, res, next) {
- var err = new Error('Not Found');
- err.status = 404;
- next(err);
- });
-
- app.set('port', 3000);
-
- var server = app.listen(app.get('port'), function() {
- console.log('Express server listening on port ' + server.address().port);
- });
-
Testing your API
We will be testing our API using postman with some sample data. You need to make sure your Mongo DB is listening to your requests. We will be testing for getting, storing, updating, and deleting todos.
- Start your node server from command prompt using this command.
-
Getting all todos.
Getting one todo.
Saving/ storing todo.
Updating/ changing todo
Deleting/ removing todo