DEV Community

Cover image for REST APIs AND MONGOOSE
Saurabh Kumar
Saurabh Kumar

Posted on

REST APIs AND MONGOOSE

Here, we are going to discuss how we can create a REST API's with mongoose. So, for this you need a basic understanding of Javascript concept, Git and NodeJs.

This is the Directory structure that we are gonna use.

So, in REST API's and Mongoose there are three main things that we are gonna touch.

  1. CRUD Operation.
  2. Creating Models.
  3. Creating Routes.

So, lets first connect out mongoose with out native mongodb.

Connect Mongoose

const mongoose = require("mongoose");
mongoose.connect('mongodb://127.0.0.1:27017/Task-M', {
useNewUrlParser: true,
useUnifiedTopology: true
})

Now, after making a proper connection with you native mongodb. Now, you can create your Models. Models are objects that save out to the data store and do basic low level manipulations on your data.
So, Now we are going to make a model for a User.

Model for a User

const User = mongoose.model('User', {
name: {
type: String,
default: "Ananomous",
trim: true
},
age: {
type: Number,
default: 0,
validate(value){
if( value < 0){
throw new Error("Age must be a positive number")
}
}
},
password :{
type: String,
trim: true,
minlength: 6,
validate(value) {
if(value.toLowerCase().includes("password")){
throw new Error("Change password")
}
}
}
})

Now we have to create an Instances of this Model

Instance -

const me = new User(
{
name: "Saurabh",
age: 21,
password: "loveSaurabh"
})

For Output -

me.save().then(() => {
console.log(me)
}).catch((error) => {
console.log('Error', error)
})

Here we are exporting our User Model to the User Router

module.exports = User;

Here, we created a Model Successfully now are are making Route on Route folder where we perform CRUD operation.

Routes Folder - CRUD Operation

Creating a User

router.post('/users', async (req, res) => {
// User Model
const user = new User(req.body)
try {
await user.save()
res.status(201).send(user)
}
catch (e) {
res.status(400).send(e)
}
})

Reading a User

// By Id
router.get('/users/:id', async (req, res) => {
const _id = req.params.id
try {
const user = await User.findById(_id)
if (!user) {
res.status(400).send("Not a User")
}
res.status(201).send(user)
}
catch (e) {
res.status(400).send(e)
}
})

Updating a User

// UPDATE
router.patch('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
runValidators: true
})
if (!user) {
return res.status(404)
}
res.status(201).send(user)
}
catch (e) {
res.status(400).send(e)
}
})

Deleting a User

// DELETE
router.delete('/users/:id', async (req, res) =>{
try{
const deleteById = await User.findByIdAndDelete(req.params.id)
if(!deleteById){
res.status(400).send("No user exist")
}
res.status(201).send(deleteById)
}
catch(e){
res.status(500).send(e)
}
})

Now we, export it on index.js Folder

module.exports = router;

INDEX.JS

const express = require('express');
const app = express();
require("./db/mongoose");
const User = require("./models/user");
const Task = require("./models/task");
const port = process.env.PORT || 3000
// Parse the JSON data
app.use(express.json())
const UserRoutes= require("./routers/user");
app.use(UserRoutes);
app.listen(port, () => {
console.log("Server is started now");
})

Now, you are all ready to test your data on POSTMAN.

Thanks for reading.

Top comments (4)

Collapse
 
shravan20 profile image
Shravan Kumar B

Do not stop at routes or controller.
Distribute the code based Separation of Concerns.

Have more layers namely controllers, services and repository

Collapse
 
saurabh37414118 profile image
Saurabh Kumar

Ok

Collapse
 
shravan20 profile image
Shravan Kumar B

Just a suggestion, write a neat articles; so it becomes readable and understandable

Collapse
 
saurabh37414118 profile image
Saurabh Kumar

Ya thanks a lot. Sir, your suggestions matter a lot, as I am a beginner in this field. I try my best, and again I just want to say a BIG thank to you. :D