Creating a Blog Using Node.js, Express & MongoDB – PART 1

Posted by


Building a blog with Node.js, Express, and MongoDB is a great way to showcase your writing and coding skills. In this tutorial, we will walk you through the process of setting up a basic blog using these technologies.

Part 1 of this tutorial will focus on setting up the backend with Node.js, Express, and MongoDB. In Part 2, we will cover setting up the frontend using HTML, CSS, and JavaScript. Let’s get started!

Step 1: Install Node.js & MongoDB
Before we start building our blog, make sure you have Node.js and MongoDB installed on your machine. If you don’t have them installed, you can download Node.js from nodejs.org and MongoDB from mongodb.com.

Step 2: Create a new Node.js project
Once you have Node.js and MongoDB installed, open your terminal and create a new directory for your project. Navigate to this directory and run the following command to initialize a new Node.js project:

npm init

Follow the prompts to set up your project. Once the initialization is complete, you will have a package.json file in your project directory.

Step 3: Install Express and other dependencies
Now that you have created a new Node.js project, we need to install Express and other dependencies that we will be using for our blog. Run the following command to install Express:

npm install express

You will also need to install other dependencies such as mongoose for MongoDB connectivity and body-parser for parsing incoming requests. Run the following command to install these dependencies:

npm install mongoose body-parser

Step 4: Set up the Express server
Now that you have installed the necessary dependencies, it’s time to set up the Express server. Create a new file called server.js in your project directory and add the following code:

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

const app = express();
const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost/blog', { useNewUrlParser: true, useUnifiedTopology: true });

// Configure body parser
app.use(bodyParser.json());

// Start the server
app.listen(port, () => {
    console.log(`Server started on http://localhost:${port}`);
});

In this code, we are setting up an Express server, connecting to MongoDB, and configuring body-parser to parse incoming requests. Replace ‘mongodb://localhost/blog’ with the connection string for your MongoDB database.

Step 5: Define the blog schema
Now that our server is set up, we need to define the schema for our blog posts in MongoDB. Create a new file called models.js in your project directory and add the following code:

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema({
    title: String,
    content: String,
    date: { type: Date, default: Date.now }
});

const Post = mongoose.model('Post', PostSchema);

module.exports = Post;

In this code, we are defining a schema for blog posts with title, content, and date fields. We are also creating a model for the posts using mongoose.

Step 6: Create endpoints for creating and fetching blog posts
Now that we have set up the schema for our blog posts, we need to create endpoints for creating and fetching posts. Update your server.js file with the following code:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Post = require('./models');

const app = express();
const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost/blog', { useNewUrlParser: true, useUnifiedTopology: true });

// Configure body parser
app.use(bodyParser.json());

// Create a new blog post
app.post('/posts', async (req, res) => {
    const { title, content } = req.body;
    const post = new Post({ title, content });

    try {
        await post.save();
        res.status(201).send(post);
    } catch (err) {
        res.status(400).send(err);
    }
});

// Fetch all blog posts
app.get('/posts', async (req, res) => {
    try {
        const posts = await Post.find();
        res.send(posts);
    } catch (err) {
        res.status(500).send(err);
    }
});

// Start the server
app.listen(port, () => {
    console.log(`Server started on http://localhost:${port}`);
});

In this code, we have added two endpoints – one for creating a new blog post and another for fetching all blog posts. The ‘post’ endpoint accepts a JSON object with title and content fields and saves the post to the database. The ‘get’ endpoint fetches all blog posts from the database and sends them as a response.

That’s it for Part 1 of this tutorial! In Part 2, we will cover setting up the frontend for our blog. Stay tuned!

0 0 votes
Article Rating

Leave a Reply

27 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@NetNinja
9 days ago

🌟Remember to subscribe to Raddy Dev's channel for more of his tutorials – https://www.youtube.com/c/RaddyDev

@jayadevpulaparty1341
9 days ago

beautiful explanation, easy to understand and practice

@KorelMedia1
9 days ago

Can't install the packages. Anyone to help on that?

@allanmachado2011
9 days ago

Love Raddy tutorials!

@charindubandaranayake7888
9 days ago

Sir, is it fine to change json type to module?

@Prabh_cc
9 days ago

Your voice is like Joe Biden…

@shai13sh
9 days ago

I would suggest that run following commands if you have warning such as "this version is no longer supported".

1) Upgrade all the dependencies to their latest versions: ncu – u

2) Install the updated dependencies: npm i

@horakbloodbow
9 days ago

Here are the shell commands you need at the start:

npm init -y

npm i bcrypt connect-mongo cookie-parser dotenv ejs express express-ejs-layouts express-session jsonwebtoken method-override mongoose

npm i -D nodemon

P.S. On Mac I was getting the "File exists" error message when attempting to install the packages, and had no luck with deleting the file. On Mac (only) sudo came to the rescue and got 'er done! – `sudo npm i –force bcrypt connect-mongo …alltheotherpackages…`

@DmitriyMalayevProfile
9 days ago

Awesome video. Thanks. Please note port 5000 is used on macs. I'm using 5001.

@chendjou7049
9 days ago

need the db

@SebastianTu-td4vk
9 days ago

This seems very similar to your Node.js crash course I just finished. Is this a sort of modernized version? I'm wondering if I should've looked around your playlists first, and this is an enhanced version of Node.js crash course

@suhanichandel8497
9 days ago

Are you using html css js??

@thechoosen4240
9 days ago

Good job bro, JESUS IS COMING BACK VERY SOON; WATCH AND PREPARE

@Astrosubho
9 days ago

Why i didn't get any thing on the browser 😢

@brotherandsister9203
9 days ago

Successfully executed the 1st video.. Let's goooooo

@hunin27
9 days ago

Hey thanks, i finished your node,js course which was pretty old and this is a pretty new and big project to do to master everything

@itsnobledean9450
9 days ago

that express ejs layout shit is breaking my app every time i use it. the fuck

@itsnobledean9450
9 days ago

this shit ain’t even working from the first fucking video

@itsnobledean9450
9 days ago

I followed every single fucking step and this shit ain’t working

@itsnobledean9450
9 days ago

I downloaded his code and this shit ain’t working

27
0
Would love your thoughts, please comment.x
()
x