Create REST API with Node and Express - Part 2

We are creating a REST API for a simple blog post that will serve blog posts and author information.

author profile image
Sakchhyam G
@saksham
Create REST API with Node and Express - Part 2

Table of content

  1. MongoDB Database
  2. Setting up MongoDB
  3. What are schema and models?
  4. Code
  5. Summary

MongoDB Database?

  • MongoDB is a no-SQL database.
  • If you are from an SQL background, a collection represents a table of rows and columns.
  • A document represents a row in a table.
  • Each document is formatted in key-value format just like a JavaScript object.

Setting up MongoDB

  • MongoDB has a cloud solution known as MongoDB Atlas platform. You can create a free shared cluster for your database.
  • Follow instructions on how to register a new Atlas account here. You can use email, GitHub account, or google account.
  • Then follow on how to deploy a free shared cluster here (Select Atlas UI tab for clear guidance).

Add a new database user

  • If you have not created a database user, follow the below steps.
  • From the sidebar, under Security, select Database Access.
Database Access  {caption: Fig.1: Database Access}
Fig.1: Database Access
  • Select +ADD NEW DATABASE USER
  • Choose Authentication Method->Password.
  • Fill in your username and password.
  • Under Built-in Role, select Atlast Admin
  • Then click the Add User button.

Add your IP address to the IP Access List

  • You should make a list of trusted IP addresses to validate access to your cluster and data.
  • You should whitelist your IP address to validate your connection with the cloud service.
  • From the sidebar, under Security, select Network Access.
Network Access {caption: Fig.2: Network Access}
Fig.2: Network Access
  • Select +ADD IP ADDRESS
  • Select the ADD CURRENT IP ADDRESS button and confirm.

Create a database in your cluster

  • From the sidebar, under Deployment select Database and then your cluster name to see an overview page.
Cluster Overview {caption: Fig.3: Cluster overview page}  {caption: Fig.6: Cluster overview page}
Fig.3: Cluster overview page
  • In the cluster's overview page, select the Collections tab. Then select the +Create Database button.
Collections Tab {caption: Fig.4: Collection tab}
Fig.4: Collection tab
  • Then fill Database Name: my-blog and Collection Name: authors
Create Database {caption: Fig.5: Create database}
Fig.5: Create database

Get the connection string for cluster

  • From the sidebar under Deployment, select Database and select your cluster.
  • Click Connect button
Cluster Overview {caption: Fig.6: Cluster overview page}
Fig.6: Cluster overview page
  • Select the Connect your application option
Connect your application {caption: Fig.7: Connect your application}
Fig.7: Connect your application
  • From the dropdown menu, select DRIVER and VERSION.
Cluster Connection String {caption: Fig.8: Connection string}
Fig.8: Connection string
  • Copy the provided connection string and go back to our project folder.

Configure the connection string

  • Place the connection string in our .env folder like this:

    1# .env 2MONGODB_ATLAS_URL="mongodb+srv://<username>:<password>@<clusterName>.wq4qj.mongodb.net/?retryWrites=true&w=majority"
  • Now replace <username> and <password> with the credential of the database user.

  • <clusterName> will be there already.

  • Add the database name after mongodb.net/. Since we have created a database named my-blog our config will look like this:

    1# .env 2MONGODB_ATLAS_URL="mongodb+srv://<username>:<password>@<clusterName>.wq4qj.mongodb.net/my-blog?retryWrites=true&w=majority"
  • Navigate to the src/config.js file and add the following line in our export:

    1... 2module.exports = { 3 port: parseInt(process.env.PORT, 10) || 5000, 4 // add this line 5 remoteDatabaseURL: process.env.MONGODB_ATLAS_URL, 6};

Use the connection string to connect with MongoDB

  • Navigate to src and create a connectDB.js file and place this code snippet:

    1// importing mongoose library to help connect with MongoDB database 2const mongoose = require("mongoose"); 3// importing config to get our connection string 4const config = require("./config"); 5 6const connectDB = async () => { 7 try { 8 // using connection string to connect with MongoDB atlas database 9 await mongoose.connect(config.remoteDatabaseURL); 10 } catch (error) { 11 console.error("Error connecting MongoDB: ", error); 12 process.exit(1); 13 } 14}; 15 16module.exports = connectDB;

What are Schema and Models?

The schema of a collection describes fields, field types, and other metadata for that collection. It is a blueprint for collection or any database entity.

From schema, we can create a constructor called Model. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database. Let's code to understand the concept.

Code

We will have two collections under the database my-blog: authors and posts. For this first, we will create the schema for each collection and export the model for each schema.

  • Navigate to the src folder and create two folders: author and post. Each folder will contain all layers for each collection.

  • Create a schema.js file inside both the author and post folder.

  • The project structure will look something like this:

    1src/ 2├─ author/ 3│ ├─ schema.js 4├─ post/ 5│ ├─ schema.js 6├─ config.js 7.env 8package.json 9server.js

author schema

  • From mongoose, we are using the Schema class to define a schema for the author.

  • The author schema will have a name, biodata, and an array of social media links.

  • Then we will create a model using schema and export it.

  • Initiating the author model will provide the necessary functions to read and write the author's documents in MongoDB database.

    1// src/author/schema.js 2const mongoose = require("mongoose"); 3const Schema = mongoose.Schema; 4 5// creating schema for author 6const schema = new Schema( 7 { 8 name: { 9 type: String, 10 require: true, 11 }, 12 bio: { 13 type: String, 14 }, 15 // defining array structure 16 socialMedia: [ 17 { 18 name: String, 19 url: String, 20 }, 21 ], 22 }, 23 { 24 // this will be our collection name in the database 25 collection: "authors", 26 } 27); 28 29// creating a model "Author" from the schema and exporting it to use in the services 30module.exports = Author = mongoose.model("Author", schema);

post schema

  • We will repeat the same steps with post schema

  • MongoDB creates a unique id (ObjectId) for each document. We will use the author's unique id in the post schema as authorRef. It will be helpful to trace out the author of a particular post.

    1// src/post/schema.js 2const mongoose = require("mongoose"); 3const Schema = mongoose.Schema; 4 5const schema = new Schema( 6 { 7 title: { 8 type: String, 9 require: true, 10 }, 11 createdDate: { 12 type: Date, 13 }, 14 content: { 15 type: String, 16 }, 17 authorRef: { 18 type: Schema.Types.ObjectId, 19 // indicates author's model name 20 ref: "Author", 21 required: true, 22 }, 23 }, 24 { 25 collection: "posts", 26 } 27); 28 29module.exports = Post = mongoose.model("Post", schema);

Summary

  • We have created a database my-blog with a collection author.
  • We got our connection string and added it to our configuration.
  • We have created schemas for the author and the post.
  • In the next part, we will take a look at services.
  • The link to the project repo is available here.
Advertisement
Advertisement