My experience creating a Blog API from scratch with Node.js and MongoDB

Introduction

BlogApi is a RESTful API that allows users to create, read, update, and delete (CRUD) blog posts. It is built using Node.js, a popular JavaScript runtime environment, and uses a MongoDB database to store blog posts.

In this write-up, we will go through the steps of setting up the development environment, creating the project, installing dependencies, setting up the database, modeling the data, and creating the API routes for the CRUD operations.

Setting up the development environment

Before we can start building the BlogApi, we need to set up our development environment by installing Node.js and MongoDB.

Installing Node.js

To install Node.js, follow these steps:

  1. Go to the official website.

  2. Click on the button for the latest stable version to download the installer.

  3. Run the installer and follow the prompts to complete the installation.

Installing MongoDB

To install MongoDB, follow these steps:

  1. Go to the official website.

  2. Click on the appropriate version and operating system to see the installation instructions.

  3. Follow the instructions to install MongoDB.

Creating the project

Now that we have our development environment set up, we can create a new project directory and initialize it with npm. npm is the package manager that comes with Node.js and is used to manage dependencies for a Node.js project.

To create a new project directory and initialize it with npm, open a terminal window and run the following commands:

mkdir blog-api
cd blog-api
npm init -y

The mkdir command creates a new directory called blogggerapi, and the cd command changes the current directory to blogggerapi. The npm init -y command initializes the project with npm and creates a package.json file in the project directory. The -y flag answers "yes" to all the prompts, so the package.json file is created with the default values.

Installing the dependencies

Next, we need to install the dependencies that our BlogApi will use.

  • express is a web framework for Node.js that makes it easy to build RESTful APIs.

  • mongoose is a MongoDB object modeling tool that simplifies the process of interacting with the database.

  • body-parser is a middleware for parsing HTTP request bodies. It is commonly used with express to parse the body of POST requests.

To install these dependencies, run the following command in the terminal:

npm install express mongoose body-parser

Setting up the database

Now, let's set up the MongoDB database that our BlogApi will use to store the blog posts.

First, start the MongoDB server by running the following command in the terminal:

mongod

This will start the MongoDB daemon, which will run in the background and listen for connections from MongoDB clients.

Next, open a new terminal window and connect to the MongoDB shell by running the following command:

mongo

This will open the MongoDB shell, which is an interactive JavaScript console that allows you to issue commands to the MongoDB server.

In the MongoDB shell, create a new database and a collection for the blog posts by running the following commands:

use blog
db.createCollection("posts")

The use command specifies which database to use, and the createCollection command creates a new collection called posts.

Modeling the data

Next, let's model the data for the blog posts using Mongoose.

Create a new file called post.js in the project directory and add the following code:

const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("Post", postSchema);

This code defines a Post model with a title and content field, both of which are required. The title field is a string, and the content field is also a string.

Creating the API routes

Now that we have our database set up and the data modeled, we can create the API routes for the CRUD operations.

Create a new file called index.js in the project directory and add the following code:

Copy codeconst express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const Post = require("./post");

const app = express();
app.use(bodyParser.json());

// Connect to the database
mongoose.connect(
  "mongodb://localhost/blog",
  { useNewUrlParser: true, useUnifiedTopology: true },
  (err) => {
    if (err) {
      console.log("Error connecting to database:", err);
    } else {
      console.log("Connected to database!");
    }
  }
);

// API routes

// Create a new post
app.post("/posts", (req, res) => {
  // Create a new post object
  const post = new Post({
    title: req.body.title,
    content: req.body.content,
  });

  // Save the post to the database
  post.save((err, post) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(201).send(post);
    }