DEV Community

Cover image for CRUD Operations In Express, Nodejs And MongoDB
Robert Look
Robert Look

Posted on

CRUD Operations In Express, Nodejs And MongoDB

in this tutorial we are learn CRUD Operations In Express, Nodejs And MongoDB. This blog may help you to get started, In this tutorial, we will be starting node.js express MongoDB crud creating a server and CRUD (Create, Read, Update and Delete) operations.
CRUD Operations In Express, Nodejs And MongoDB
This is image title

Database Connectivity mongoose

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mongooseCRUD', {useNewUrlParser: true}, 
(err) => {
    if (!err) {
        console.log('Successfully Established Connection with MongoDB')
    }
    else {
        console.log('Failed to Establish Connection with MongoDB with Error: '+ err)
    }
});
module.exports = mongoose;
Enter fullscreen mode Exit fullscreen mode

All User Controller function

const express = require("express")
const User = require("../models/users")
const router = express.Router()
/**
 * User controller : All business logic goes here
 */
// Insert
router.post("/", async (req, res)=>{
    const user= new User({
        name: req.body.name
        email: req.body.email
    })
    try{
        let users= await user.save()
        res.status(200).json({
            status: 1,
            data: users
        })
    } catch(err){
        res.status(500).json({
            Message:err.message
        })
    }
})

/** 
 * Find all Users
 */

router.get("/", async (req, res)=>{
    try{
        let users= await User.find();
        res.status(200).json(users)
    } catch(err){
        res.status(500).json({
            Message:err.message
        })
    }
})

/** 
 * Find One Users
 */

router.get("/:id", async (req, res)=>{
    try{
        let users= await User.findById(req.params.id);
        res.status(200).json(users)
    } catch(err){
        res.status(500).json({
            Message:err.message
        })
    }

/** 
 * Remove One User
 */
router.delete("/:id", async (req, res)=>{
    try{
        let users= await User.findByIdAndRemove(req.params.id);
        res.status(200).json({
            message: "User deleted successfully!",
            Data: users
        })
    } catch(err){
        res.status(500).json({
            Message:err.message
        })
    }
})

/**
 * Update a user with the specified id in the request
 */
router.put("/:id", async (req, res)=>{
    try{
        let users= await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
        res.status(200).json({
            message: "User Updated successfully!",
            Data: users
        })
    } catch(err){
        res.status(500).json({
            Message:err.message
        })
    }
module.exports = router
Enter fullscreen mode Exit fullscreen mode

Working with Routes.

/**
 * This code rootfile is a linke (index.js, app.js, server.js)
 */
const express = require('express')

const app = express()

const port = 3000

const mongoose = require('mongoose')

app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.use(express.json());

const userRouter = require("./routes/users")

app.use('/user', userRouter)

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Original source: https://www.phpcodingstuff.com/blog/crud-operations-in-express-nodejs-and-mongodb.html

Top comments (0)