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

Chuk Orakwusi
2 min readDec 6, 2020

A key aspect of programming is to always ensure your code is readable and also structured in a way that ensures that there’s flow. The “app.js” file can get cluttered quite quickly with lots of code so when you can, to avoid constantly scrolling to reach the line of code you need to amend, split your code into separate files and folders. I’ve created a folder called “routes” and within that folder, a file called “posts.js”.

At the top of the “posts.js” file, add:

const express = require('express');const router = express.Router();

What’s achievable with this file splitting structure is that we can have the routes in separate files and import them into the “app.js” file. In the posts file, we can now use “router” instead of “app” to build routes. For example, the route to the home page in “app.js”

app.get('/posts', (req, res) => {
res.send("Homepage");
});

Can now be changed to

router.get('/posts', (req, res) => {
res.send("Homepage");
});

Also add “module.exports = router” to export the router. We can add the route to the “app.js” file via a middleware. In “app.js”, add the following

const postsRoute = require('./routes/posts');

Then add the middleware which ensures that whenever the user goes to “/posts”, postsRoute kicks in.

To create data for the database, we’ll need to utilise Mongoose. Create a new folder called “models” and within that folder, create a file called “Post.js” (notice the first letter is in uppercase). At the top of the file add:

const mongoose = require('mongoose');

Now we’ll need to created a schema using mongoose so, type in:

const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
})

The schema, with validations, gives a blueprint of the data that will be added and what it should look like when it’s returned. The validations also ensure that users fill out all the criteria. This ensures that when a user posts, there’s always a title with the description and a date which will default to the current date if none is added.

And finally, we’ll add

module.exports = mongoose.model('Posts', PostSchema);

‘Posts’ is the name given to the model and this reference will appear in MongoDB and we pass “PostSchema” which is the schema that will be used when data is passed in.

--

--