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

Chuk Orakwusi
2 min readDec 20, 2020

To get a specific post, you’ll use the Post model and an inbuilt method, “findById”. As it could take some time because it’s pulling from a database, add “async” and “await”.

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

To delete a specific post, you’ll need to use the Post model again. Add “_id” because this is the parameter MongoDB generates per object.

router.delete('/:postId', async(req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId})
res.json(removedPost);
} catch (err) {
res.json({ message: err })
}
})

To update a specific post, you’ll need to use the specific post Id, use the Post model and an inbuilt method, “updateOne”. Remember to still use “async” and “await” as you’ll be interacting with a database on MongoDB. Wrap it in a “try/catch”. Store the action in a variable which will take two objects: one object will be the search criteria and the second object will specify which parameter is being updated.

router.patch('/:postId', async(req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{ $set: {title: req.body.title} }
);
res.json(updatedPost);
} catch (err) {
res.json ({ message: err });
}
})

Et voila! This is all you need to do to set up a Restful API with express and MongoDB. You can now use this for your front-end application. As you’ll be fetching across different domains, you likely get a CORS error. To avoid that, go back into your project, install cors.

npm install cors

After installation, go into “app.js”, import cors add the middleware.

const cors = require('cors');
app.use(cors());

With this installed and added, you can now fetch and your app should be working!

--

--