Building Simple Rest API using Express and MongoDB Atlas
In this article, we will implement a simple rest service using Node Js, Express js, and Mongoose. We are going to connect our simple CRUD application to Mongo DB Atlas.
First, you need to have a MongoDB Atlas account and it is free. After creating your account login with your account and then create a Cluster.
Setting up MongoDB Atlas
Then select the free Shared/Starter cluster
Select Cloud Provider & Region
Then select Create Cluster at the bottom of the page. Once the Cluster is created create a new Database User. It can be any name just give a proper username and password.
Then go to the Network Access page and select ADD IP ADDRESS. Select the current IP address and ignore comments and click confirm.
Then select Cluster from the sidebar & click connect and this box will pop up.
Select Connect your application and now you can copy the connection string.
When you are going to use this in your express application you need to replace the <password> with the password you created for the database user. And also replace the myFirstDatabase with your database name.
Now create a folder and give any name and open the folder with any code editor.
mkdir my-app
cd my-app
Then we need to init our project folder and this will create a package.json file.
npm init -y
Now install express and mongoose using the below command.
npm install express mongoose
Now create a file called index.js inside our project folder. We need to create an express server.
const express = require('express')
const app = express();
app.listen(3000, () => {
console.log("Server is running on port 3000!");
});
Now we can test our express server is running by using the below command. Make sure that “main”: “index.js”, is index.js inside package.json.
node index.js
Now modify the index.js file according to the below code.
const express = require('express')
const mongoose = require('mongoose')
const app = express();
mongoose.connect('yourconnectionstring', {
useNewUrlParser: true,
useUnifiedTopology: true
}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(3000, () => {
console.log("Server is running on port 3000!");
});
Now we need to create a model for the database. Create models folder.
mkdir models
Now create a file called Post.model.js and copy and paste the below code.
const mongoose = require('mongoose')
const schema = mongoose.Schema;
const PostSchema = new schema({
name: {
type: String
},
description: {
type: String
}
});
const Post = mongoose.model('Post', PostSchema);
module.exports = Post;
Now create a directory called routes and inside that directory create a file named posts.routes.js.
mkdir routestouch posts.routes.js
Inside posts.routes.js paste the below code to get all posts.
const express = require('express')
const Post = require("../models/Post.model") //Importing model
const router = express.Router()
router.get("/", async (req, res) => {
const posts = await Post.find()
res.send(posts)
})module.exports = router
Modify index.js in order to import the Post router.
const express = require("express")
const cors = require('cors');
const mongoose = require("mongoose")
const app = express();
app.use(cors());
app.use(express.json());
mongoose.connect('yourconnectionstring', {
useNewUrlParser: true,
useUnifiedTopology: true
}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const postRouter = require('./routes/posts.routes');
app.use('/posts', postRouter);
app.listen(3000, () => {
console.log("Server is running on port 3000!");
});
Now when trying to access http://localhost:3000/posts, we can see an empty array.
Add new Post
Now we will modify our posts.routes.js to add a new item.
const express = require('express')
const Post = require("../models/Post.model")
const router = express.Router()
router.get("/", async (req, res) => {
const posts = await Post.find()
res.send(posts)
})router.post("/", async (req, res) => {
const post = new Post({
name: req.body.name,
description: req.body.description,
})
await post.save()
res.send(post)
})module.exports = router
Now we can test our create post method using Postman. You can download Postman if don't have it from the below link. It is very useful for API testing.
Now when you create a JSON object and click send then a new post will be created. Create more than one post in order to test the rest of our methods.
Now when trying to access http://localhost:3000/posts, we can see an array with some value.
Get one post
Now we will modify our posts.routes.js to get one post.
const express = require('express')
const Post = require("../models/Post.model")
const router = express.Router()
router.get("/", async (req, res) => {
const posts = await Post.find()
res.send(posts)
})
router.post("/", async (req, res) => {
const post = new Post({
name: req.body.name,
description: req.body.description,
})
await post.save()
res.send(post)
})
// Get one post
router.get("/:id", async (req, res) => {
try {
const post = await Post.findOne({_id: req.params.id})
res.send(post)
} catch {
res.status(404)
res.send({error: "Post not found."})
}
})module.exports = router
Now using when trying to use the GET method with http://localhost:3000/id, we can see only the post with that id. Using Postman you can test this. (id is the id of the created post)
Update
Now we will modify our posts.routes.js to update an item.
const express = require('express')
const Post = require("../models/Post.model")
const router = express.Router()
router.get("/", async (req, res) => {
const posts = await Post.find()
res.send(posts)
})
router.post("/", async (req, res) => {
const post = new Post({
name: req.body.name,
description: req.body.description,
})
await post.save()
res.send(post)
})
// Get one post
router.get("/:id", async (req, res) => {
try {
const post = await Post.findOne({_id: req.params.id})
res.send(post)
} catch {
res.status(404)
res.send({error: "Post not found."})
}
})
// Update a post
router.patch("/:id", async (req, res) => {
try {
const post = await Post.findOne({_id: req.params.id})
if (req.body.name) {
post.name = req.body.name
}
if (req.body.description) {
post.description = req.body.description
}
await post.save()
res.send(post)
} catch {
res.status(404)
res.send({error: "Post not found."})
}
})module.exports = router
We can test the update method using Postman as below.
Delete
Now we will modify our posts.routes.js to delete a post.
const express = require('express')
const Post = require("../models/Post.model")
const router = express.Router()
router.get("/", async (req, res) => {
const posts = await Post.find()
res.send(posts)
})
router.post("/", async (req, res) => {
const post = new Post({
name: req.body.name,
description: req.body.description,
})
await post.save()
res.send(post)
})
// Get one post
router.get("/:id", async (req, res) => {
try {
const post = await Post.findOne({_id: req.params.id})
res.send(post)
} catch {
res.status(404)
res.send({error: "Post not found."})
}
})
// Update a post
router.patch("/:id", async (req, res) => {
try {
const post = await Post.findOne({_id: req.params.id})
if (req.body.name) {
post.name = req.body.name
}
if (req.body.description) {
post.description = req.body.description
}
await post.save()
res.send(post)
} catch {
res.status(404)
res.send({error: "Post not found."})
}
})
// Delete a Post
router.delete("/:id", async (req, res) => {
try {
await Post.deleteOne({_id: req.params.id})
res.status(204).send()
} catch {
res.status(404)
res.send({error: "Post not found."})
}
})
module.exports = router
You can use Postman to test the delete method also.
Now when we test the existing posts by going to http://localhost:3000/posts, you will that the post with that id has been removed.
So, here I have demonstrated a simple REST API using express and Mongo DB Atlas. I hope that should give you some understanding of building a Rest API.