DEV Community

Cover image for Content Management System: Building a Post Creation System from Scratch with Node js
WebCraft Notes
WebCraft Notes

Posted on • Originally published at webcraft-notes.com

Content Management System: Building a Post Creation System from Scratch with Node js

If you will need a source code for this tutorial you can get it here.

Building a content management system is an exciting journey, and today we're diving into its core functionality - post creation. In this comprehensive guide, we'll walk through implementing a robust post management system from the ground up. We'll start by establishing a solid backend foundation with Node.js, setting up the necessary routes, models, and controllers. Then, we'll move forward to create an intuitive frontend interface that integrates with our API.

This approach - beginning with the backend and then progressing to the frontend - will help us understand the complete data flow and ensure a well-structured application architecture. So let's start from building the typical "post schema", probably while developing or adding more features to the post we will modify it's schema, but for now we will add simple necessary fields.

1. Setting Up the Post Model (MongoDB Schema)

In one of our previous articles, we created our first "user" schema. Now we need to repeat this process, but only for our article entity. Let's do it:

  • define necessary "post" fields. For example, I will set fields like title, subtitle, three meta fields (keywords, description, and schema), URL, language, status, archive, created, updated, and body (Array), which will store a list of text parts... ;

  • create new "posts" folder inside the "models" folder;

  • add new "posts.mongo.js" file;

  • import "mongoose" and define a new "postSchema" with the "mongoose.Schema" method;

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        default: ''
    },
    subTitle: {
        type: String,
        default: ''
    },
    status: {
        type: String,
        default: ''
    },
    archived: {
        type: Boolean,
        default: false
    },
    slug: {
        type: String,
        default: ''
    },
    language: {
        type: String,
        default: ''
    },
    created: {
        date: {
            day: {
                type: String,
                default: ''
            },
            month: {
                type: String,
                default: ''
            },
            year: {
                type: String,
                default: ''
            },
            time: {
                type: String,
                default: ''
            }
        },
        user: {
            type: String,
            default: ''
        }
    },
    updated: {
        date: {
            day: {
                type: String,
                default: ''
            },
            month: {
                type: String,
                default: ''
            },
            year: {
                type: String,
                default: ''
            },
            time: {
                type: String,
                default: ''
            }
        },
        user: {
            type: String,
            default: ''
        }
    },
    meta: {
        description: {
            type: String,
            default: ''
        },
        keywords: {
            type: String,
            default: ''
        },
        schema: {
            type: String,
            default: ''
        }
    },
    body: [
        {
            type: {
                type: String,
                default: ''
            },
            content: {
                type: String,
                default: ''
            },
        }
    ],
});

module.exports = mongoose.model('Post', postSchema);
Enter fullscreen mode Exit fullscreen mode

Something like that. You can change those fields, depending on your post structure. Okay, let's move to creating new post functionality.

2. Creating Post Functions (Service Layer)

In this section, we need to simply add a function that will get the post as a payload and save it in our "posts" db.

  • import our "posts" schema from "posts.mongo";

  • add a "createNewPost" function with the "mongoose" create method;

async function createNewPost(payload) {
    try {
        const newPost = await posts.create(payload);
        return newPost;
    } catch (error) {
        console.error('Error creating new post:', error);
        throw error;
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Establishing Post Routes (API Endpoints)

The most interesting part is where we will define the new "posts" API group with the first route.

  • create a new "posts" folder inside the "routes" directory;

  • add new "posts.router.js" file, where we need to import express, define new "postsRouter" and set the first post route;

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

postsRouter.post('/create', postsController.createNewPost);

module.exports = postsRouter;
Enter fullscreen mode Exit fullscreen mode
  • inside the "api.js" file import and use our posts routes;
const express = require('express');
const usersRouter = require('./users/users.router');
const postsRouter = require('./posts/posts.router');
const api = express.Router();

api.use('/api/users', usersRouter);
api.use('/api/posts', postsRouter);

module.exports = api;
Enter fullscreen mode Exit fullscreen mode

That's it, now we have the first post route that should trigger "controller" which we will define in the next part and save a new post.

4. Building the Post Controller

It will be a simple controller that will receive a post from the request body, use the "createNewPost" function from the post model, and return some result (success or error, if success then it's a good fit to return the created post).

async function createNewPost(req, res) {
    const { post } = req.body;
    if (!post) {
        return res.status(400).json({
            status: 400,
            message: 'Post is required'
        });
    }
    try {
        const newPost = await postsModel.createNewPost(post);
        return res.status(200).json({
            status: 200,
            message: 'Post created successfully',
            post: newPost
        });
    } catch (error) {
        return res.status(500).json({
            status: 500,
            message: 'Internal server error'
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Awesome, we did it, we prepared our backend infrastructure to accept and save post from the client side.

In this guide, we've successfully built a foundational backend structure for post creation in our content management system. We've covered all essential components:

Created a flexible MongoDB schema that can accommodate various post attributes
Implemented a service layer with a robust post creation function
Set up API routing with Express
Built a controller to handle post creation requests with proper error handling
This backend infrastructure now serves as a solid foundation for building the frontend interface. With these components in place, you can now securely create and store posts in your CMS, and easily extend the functionality to include features like post updating, deletion, and retrieval.

In the next article, we'll focus on building the frontend interface that will interact with these endpoints, allowing users to create posts through an intuitive UI. See you on the next article and Happy Coding!

If you need a source code for this tutorial you can get it here.

Found this post useful? ☕ A coffee-sized contribution goes a long way in keeping me inspired! Thank you)
Buy Me A Coffee

Next step: "React Post Creation Form: Building the Frontend for Your Content Management System"

Top comments (1)

Collapse
 
shiza_beyg_c9770eb78a8a1f profile image
Shiza Beyg

Through content marketing, brands can build awareness by consistently sharing their stories, mission, and values. By creating content that resonates with the audience, companies position themselves as thought leaders in their industry.