Building A RESTful API: Express.js & MongoDB -Part 4

Chuk Orakwusi
2 min readDec 13, 2020

To create a post, firstly, import the model that will be receiving the post. At the top of ‘posts.js’, import the model by typing in the following:

const Post = require('../models/Post');

Within the body of ‘posts.js’, type in

router.post('/', (req, res) => {
});

To handle a ‘HTTP POST’ request in, you’ll need to install a middleware module called ‘body-parser’. This will extract the entire body of an incoming request and deliver it on ‘req.body’. It parses the JSON, buffer, string and URL encoded data submitted using ‘HTTP POST’ request. To install this, run

npm install body-parser

In ‘app.js’, you’ll need to import body-parser so at the top of the file, add

const bodyParser = require('body-parser');

To ensure that it runs, still in ‘app.js’, add:

app.use(bodyParser.json());

Back in ‘posts.js’, in your posts requests, pass in an object

router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.exec()
.then(data => {
res.json(data)
});
.catch(err => {
res.json({ message: err });
});
});

post.save() ensures that the post is saved to the database. “.exec()” returns a promise and ‘.then’ responds with json data that will be persisted to the database. You can also add ‘.catch’ for any errors. To make the code async and cleaner, it can be amended to the below:

router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err })
}
});

To receive all the posts, you’ll need to amend the get router.

router.get('/', async (req, res) => {
try{
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});

--

--