Node.js from Beginners to Advance: Part - 2
REST API using node, express and MongoDB
This is the second part of the node series; if you're unfamiliar with node, don't worry; we covered everything in the first series, which you can find it here => dev.to/aviyel/node-js-from-beginners-to-advance
So, without further ado, let's get this party started.
So, what exactly is MongoDB?
MongoDB is a cross-platform document-oriented database application that is open source. MongoDB is a NoSQL database application that works with JSON-like documents and optional schemas. MongoDB is a database that was created by MongoDB Inc. and is distributed under the Server Side Public License.
Now, Let's get this project started right away.
Getting started on our project
Create a new folder and name it whatever you like, then open it in Visual Studio Code and run the code below from the command prompt.
npm init -y
Configuring package.json
To install the dependencies, use the following instructions in the terminal.
npm i dotenv cors mongoose express nodemon
dotenv: It is needed to retrieve data from.env files.
express: node.js web application framework.
mongoose: It is a Node. js based Object Data Modeling (ODM) library for MongoDB
nodemon: It will keep the server running indefinitely.
cors: It allows cross-origin API requests.
The "package.json" file should look like this after the dependencies have been installed.
{
"name":"rest",
"version":"1.0.0",
"description":"",
"main":"index.js",
"scripts":{
"start":"nodemon server.js"
},
"keywords":[],
"author":"",
"license":"ISC",
"dependencies":{
"cors":"^2.8.5",
"dotenv":"^10.0.0",
"express":"^4.17.1",
"mongoose":"^6.0.8",
"nodemon":"^2.0.13"
}
}
And also, remember to update the scripts as well.
Structuring the folder:
controllers: The files in the controllers’ folder will contain the methods for the endpoints to interface with the database.
models: The files that specify the MongoDB schema will be found in the model’s folder.
dbConfig: Make a file called db.js in the config folder. The necessary code for connecting to the MongoDB database will be contained in this file.
routers: The files with the endpoints will be found in the routers folder.
Configuring server.js
Import express and use express() to start our app.
Using the app, create a get method for the endpoint http://localhost:6000.
For our server to run, set the PORT to 6000.
Using our app, you may listen to PORT.
//app.js
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
// listen
app.listen(PORT, () =>
console.log(`Server is running on http://localhost:${PORT}`)
);
Now use the following code to start the server with nodemon. Ensure that the following command is executed from the project directory.
npm start
If the server has started successfully, the terminal should display the following message.
Getting started with MongoDB
Sign in to MongoDB
Make a new project.
- Create a cluster
- Choose a cloud service provider.
Make a cluster
Wait for the cluster to be built before proceeding (usually takes around 5 -10 minutes)
- Allow access from anywhere by clicking connect. Then IP address should be added.
Create a user in the database. For the MongoDB URI, you'll need the username and password.
Select a connection method by clicking on it.
Connect your application by clicking on it.
Choose the appropriate driver and version.
Copy and paste mongodb+srv into the.env file.
PORT=6000
MONGO_DB_URL=mongodb+srv://admin:-----------@cluster0.2qee0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
Now open the database.js file in the dbConfig folder and make the modifications listed below.
Import Mongoose.
MONGO_DB_URL should be imported from the.env file.
Define the configDatabase method for establishing a database connection.
The configDatabase method should be exported and called in server.js.
//database.js
const mongoose = require("mongoose");
require("dotenv").config();
const dbURL = process.env.MONGO_DB_URL;
const configDatabase = async () => {
try {
await mongoose.connect(dbURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("Database connected");
} catch (err) {
console.log(err);
process.exit(1);
}
};
module.exports = configDatabase;
Add the following changes on server.js file
// server.js
const express = require("express");
const cors = require("cors");
const configDatabase = require("./dbConfig/database.js");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
//connecting to the mongodb database
configDatabase();
app.use(cors({ origin: true, credentials: true }));
// add the middlewares
app.use(express.json({ extended: false }));
app.get("/", (req, res) =>
res.send("Hello there!! Cheers !! The server is up and running")
);
// listen
app.listen(PORT, () =>
console.log(`Server is running on http://localhost:${PORT}`)
Defining database schema:
Add a todo.models.js file inside the models folder. We will define the entire db schema inside this particular file.
// todo.models.js
const mongoose = require("mongoose");
const TodoListSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
const Todo = mongoose.model("todo", TodoListSchema);
module.exports = Todo;
Defining the entire endpoint of our API
// todo.routes.js
const express = require("express");
const router = express.Router();
const {
listAllTodo,
createTodo,
updateTodo,
deleteTodo,
} = require("../controllers/todo.controller.js");
router.get("/", listAllTodo);
router.post("/", createTodo);
router.put("/:id", updateTodo);
router.delete("/:id", deleteTodo);
module.exports = router;
Defining the methods for our endpoint
The methods for the endpoints will be defined in the controllers’ folder.
The first step is to import the todo models.
const Todo = require("../models/todo.models.js");
listAllTodo() : find() method will return all the todo inside the MongoDB collections.
exports.listAllTodo = (req, res) => {
Todo.find()
.then((todo) => {
console.log({ todo });
res.json(todo);
})
.catch((err) => {
res
.status(404)
.json({ message: "There isnt any todo available", error: err.message });
});
};
createTodo(): The method create() will create a todo item and return a success message.
exports.createTodo = (req, res) => {
Todo.create(req.body)
.then((todo) => {
console.log({ todo });
res.json({
message: "Cheers!! You have successfully added TODO",
todo,
});
})
.catch((err) => {
res.status(404).json({
message: "Sorry your todo list cannot be added",
error: err.message,
});
});
};
Full article available here => https://aviyel.com/post/1150
Follow @aviyelHQ or sign-up on Aviyel for early access if you are a project maintainer, contributor, or just an Open Source enthusiast.
Join Aviyel's Discord => Aviyel's world
Twitter =>https://twitter.com/AviyelHq