Build a simple blog with Node.js, Express, MongoDB (Part 4)

At first, let's install MongoDB http://blog.alphaplus.vn/2017/08/how-to-install-mongodb-on-ubuntu.html, robomongo (optional) http://blog.alphaplus.vn/2017/08/robomongo-native-and-cross-platform-mongodb-manager.html and postman http://blog.alphaplus.vn/2017/08/postman-complete-api-development.html.

We will use RESTful (REpresentational State Transfer) web services to interact with the resources.
  • GET: receive the resource representation
  • POST: add some information to the resource
  • PATCH: modify the resources
  • DELETE: delete the resources

Why Web Services?

Interoperability - Other applications can also use the web services. For example, a VB, .NET, PHP, Ruby, Python or mobile application can talk to our web services.

We will create 5 different routes in our application:
HTTP Verb Path Used for
GET /posts display a list of all posts
POST /posts create a new post
GET /posts/:id display a specific post
PATCH /posts/:id update a specific post
DELETE /posts/:id delete a specific post

It's easy! Open server.js and add the following:
app.get('/posts', (req, res) => {
  res.send('Display a list of all posts.');
});
app.post('/posts', (req, res) => {
  res.send('Create a new post.');
});
app.get('/posts/:id', (req, res) => {
  res.send(`Display a specific post (ID: ${req.params.id}).`);
});
app.patch('/posts/:id', (req, res) => {
  res.send(`Update a specific post (ID: ${req.params.id}).`);
});
app.delete('/posts/:id', (req, res) => {
  res.send(`Delete a specific post (ID: ${req.params.id}).`);
});


Run the following command:
$ nodemon server.js

Then use postman to check all routes above.

We will use body-parser package https://www.npmjs.com/package/body-parser
This module provides the following parsers:
  • JSON body parser
  • Raw body parser
  • Text body parser
  • URL-encoded form body parser

Run the following command to install:
$ npm install body-parser --save

Add these lines to server.js:
const bodyParser = require('body-parser');
and
app.use(bodyParser.json());

It works as expected? Now we are going to interact with MongoDB, a NoSQL document database.

NoSQL vocabularies

Relational Database NoSQL Database
Database Database
Table Collection
Row/ Record Document
Column Field

Interact with MongoDB

To interact with MongoDB, we use mongodb package https://www.npmjs.com/package/mongodb
$ npm install mongodb --save

Let's create a new post first, then we will display a list of all posts, display a specific post, update a specific post and delete a specific post.

Follow the instruction at https://www.npmjs.com/package/mongodb, we add the following lines to server.js:
const MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/blogs';

(with blogs is the database name and 27017 is the port when set up MongoDB)

Create a new post

Replace
app.post('/posts', (req, res) => {
// ...
});
with the code to insert a document to "posts" collection:
app.post('/posts', (req, res) => {
  MongoClient.connect(url, (err, db) => {
    if (err) {
      res.send("Can't connect to MongoDB.");
    } else {
      db.collection('posts')
        .insertOne({
          title: req.body.title,
          content: req.body.content
        }, (err, result) => {
          if (err) {
            res.send('An error has been occurred while creating a new post.');
          } else {
            res.send(result.ops);
          }
        });
    }
  });
});


Open postman and test:

Use Robomongo to the check new post in the database



Display a list of all posts

Replace:
app.get('/posts', (req, res) => {
// ...
});

with:
app.get('/posts', (req, res) => {
  MongoClient.connect(url, (err, db) => {
    if (err) {
      res.send("Can't connect to MongoDB.");
    } else {
      db.collection('posts')
        .find()
        .toArray((err, docs) => {
          if (err) {
            res.send('An error has been occurred while displaying a list of all posts.');
          } else {
            res.send(docs);
          }
        });
    }
  });
});


Open postman and test:

Display a specific post

"_id" field isn't a string, it's an ObjectId type. So, we add to server.js:
const ObjectId = require('mongodb').ObjectId;

Or we change:
const MongoClient = require('mongodb').MongoClient;
to
const {MongoClient, ObjectId} = require('mongodb');

Then change:
app.get('/posts/:id', (req, res) => {
// ...
});

to
app.get('/posts/:id', (req, res) => {
  MongoClient.connect(url, (err, db) => {
    if (err) {
      res.send("Can't connect to MongoDB.");
    } else {
      db.collection('posts')
        .findOne({_id: new ObjectId(req.params.id)}, (err, doc) => {
          if (err) {
            res.send('An error has been occurred while displaying a specific post.');
          } else {
            res.send(doc);
          }
        });
    }
  });
});

Update a specific post

Change:
app.patch('/posts/:id', (req, res) => {
// ...
});


to:
app.patch('/posts/:id', (req, res) => {
  MongoClient.connect(url, (err, db) => {
    if (err) {
      res.send("Can't connect to MongoDB.");
    } else {
      db.collection('posts')
        .updateOne(
          {_id: new ObjectId(req.params.id)},
          {
            $set: {
              title: req.body.title,
              content: req.body.content
            }
          },
          (err, result) => {
          if (err) {
            res.send('An error has been occurred while updating a specific post.');
          } else {
            res.send(result);
          }
        });
    }
  });
});


Open postman and test:


Open Robomongo to check:


Delete a specific post

Change:
app.delete('/posts/:id', (req, res) => {
// ...
});


to:
app.delete('/posts/:id', (req, res) => {
  MongoClient.connect(url, (err, db) => {
    if (err) {
      res.send("Can't connect to MongoDB.");
    } else {
      db.collection('posts')
        .deleteOne({_id: new ObjectId(req.params.id)}, (err, result) => {
          if (err) {
            res.send('An error has been occurred while deleting a specific post.');
          } else {
            res.send(result);
          }
        });
    }
  });
});


Open postman and test:

Then open Robomongo to check:


OK, that's it.
In part 5, we are going to use https://www.npmjs.com/package/mongoose.

Part 5: http://blog.alphaplus.vn/2017/09/build-simple-blog-with-nodejs-express-mongodb-part-5.html
See you then.

No comments:

Post a Comment