webbuild infotech

crud-in-node

CRUD API in ExpressJS and NodeJS with MongoDB

ExpressJS is a Framework of NodeJS that is most often used as a backend application in a client-server architecture. And it’s designed to help JavaScript developers create servers really quickly. NodeJS may be server-side, but it can do a whole lot more than just serve pages and data.

I presume that you already installed NodeJS and MongoDB on your machine. If you don’t have it installed, kindly go through this link on how to install it in order for us to create a server in Node and MongoDB.

Please run npm -v and mongo --version as these will show you the version of NPM and MongoDB installed on your machine.

If you do have Node and MongoDB installed, let’s begin with the following basic steps.

Step 1: Please create the project from the terminal. and it will generate the folder structure as given below.

sample-folder-structure

Step 2: Now let’s go to the project and first of all, connect the database where we can use MongoDB, MySql, etc.., but these things depend on the developer and project requirements but we are going to use the MongoDB database in the example.

So install mongoose with npm install mongoose the package and create config/db.js   where connect the database.

const mongoose = require("mongoose");
require('dotenv').config();
// Replace this with your MONGOURI.
const MONGOURI = process.env.DATABSE_CONNECTION 
const InitiateMongoServer = async () => {
  try {
    await mongoose.connect(MONGOURI, {
      useNewUrlParser: true
    });
    console.log("Connected to DB !!");
  } catch (e) {
    console.log(e);
    throw e;
  }
};
module.exports = InitiateMongoServer;

In the above example, there is process.env.DATABSE_CONNECTION so instead of that connect with a direct URL like mongodb://localhost:27017/users or set the URL in .env file.

Step 3:  Now create the Schema in Model/User.js and its uses for making data types for fields and validation etc.

const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
  firstname : { type: String, required: true },
  lastname : { type: String, required: true },
  email: { type: String, required: true },
  role: { type: String, require: true, 
          enum: ['Artist','Designer','Art Manager'] 
        },
  image: { type: String, default: null },
  status: { type: Number, default: 1, enum: [1, 0] },
  is_deleted: { type: Number, default: 0, enum: [1, 0] },
  createdAt: { type: Date, default: Date.now },
  modifiedAt: { type: Date, default: Date.now },
});
// export model user with UserSchema
module.exports = mongoose.model("user", UserSchema);

Step 4: Now let’s create the routes for the users in routes folder routes/users.js  and import Schema and Validator.

var express = require('express');
var router = express.Router();
const { check, validationResult} = require("express-validator/check");
const User = require("../model/User");

Now let’s create the users Listing API

/* GET users listing. */
router.get('/', function(req, res) {
  try {
    User.find().then(users => {
      res.status(200).send({ 
        users : users,
        message : "User has been fetch successfully!"
      });
    }).catch(err => {
      res.status(500).send({
         message: err.message || "Some error occurred while retrieving notes."
      });
    });
  } catch (err) {
    res.status(500).send({message : "Error in Saving"});
  }
});

Now let’s create the user Create API

/**
 * @method - POST
 * @param - /crete
 * @description - User Create
 */

router.post("/create",[
      check("firstname", "Please Enter a Valid Firstname").not().isEmpty(),
      check("lastname", "Please Enter a Valid Lastname").not().isEmpty(),
      check("role", "Please Enter a Valid role").not().isEmpty(),
      check("email", "Please enter a valid email").isEmail(),
    ],
    async (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array(),
        });
      }
        const {  firstname, lastname, role, email } = req.body;
        try {
            let user = await User.findOne({ email});
            if (user) {
                return res.status(400).json({
                    message: "User Already Exists"
                });
            }
            
            user = new User({firstname , lastname, role, email});
            await user.save();
            const payload = { user: { id: user.id} };
            return res.status(200).json({
              user : user,
              message : 'User has been created successfully!'
            });
        } catch (err) {
          console.log('err',err);
          res.status(500).send({message : "Error in Saving"});
        }
    }
);

Now let’s create the user Update API

/**
 * @method - POST
 * @param - /update
 * @description - User Update
 */
router.post("/update/:Id",[
      check("firstname", "Please Enter a Valid Firstname").not().isEmpty(),
      check("lastname", "Please Enter a Valid Lastname").not().isEmpty(),
      check("role", "Please Enter a Valid role").not().isEmpty(),
      check("email", "Please enter a valid email").isEmail(),
    ],

    async (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array()
        });
      }

      let user = await User.findById(req.params.Id);
      if (!user && user.role != 'Art Manager') {
        let userdata = await User.findOne({ email});
        if (userdata) {
            return res.status(400).json({
                message: "User Already Exists"
            });
        }
      }

      const { firstname, lastname, role, email } = req.body;
      try {
        // Find user and update it with the request body
        User.findByIdAndUpdate(req.params.Id, {
          firstname :  firstname,
          lastname : lastname,
          role : role,
          email : email
          }, {new: true}).then(user => {
            if(!user) {
                return res.status(404).send({
                    message: "User not found with id " + req.params.Id
                });
            }
            res.status(200).send({
              user : user,
              message : 'User has been updated successfuly!'
            });
          }).catch(err => {
            if(err.kind === 'ObjectId') {
                return res.status(404).send({
                    message: "User not found with id " + req.params.Id
                });                
            }
            return res.status(500).send({
                message: "Error updating user with id " + req.params.Id
            });
          });
      } catch (err) {
          res.status(500).send({message:"Error in updating"});
      }
    });

Now let’s create the user Delete API

/**
 * @method -  GET
 * @description - DELETE User
 * @param - /user/delete
 */
router.get("/delete/:Id", async (req, res) => {
  try {
    User.findByIdAndRemove(req.params.Id)
    .then(user => {
        if(!user) {
            return res.status(404).send({
                message: "User not found with id " + req.params.Id
            });
        }
        res.send({message: "User deleted successfully!"});
    }).catch(err => {
        if(err.kind === 'ObjectId' || err.name === 'NotFound') {
            return res.status(404).send({
                message: "User not found with id " + req.params.Id
            });                
        }
        return res.status(500).send({
            message: "Could not delete user with id " + req.params.Id
        });
    });
  } catch (e) {
    res.send({ message: "Error in Fetching user" });
  }
});

Step 5: A model/user.js, config/db.s and routes/users.js  created so these things need to import into app.js file and some package as well.

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
var logger = require('morgan');
const cors = require("cors"); // Enable All CORS Requests
require('dotenv').config();

const InitiateMongoServer = require("./config/db");
// Initiate Mongo Server
InitiateMongoServer();

var usersRouter = require('./routes/users');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Enable All CORS Requests
app.use(cors());

app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Step 6: Now open the terminal in the current directory and press the npm start command or either nodemon start and check API in postman.

Note: nodemon is a tool that helps develop node. js based applications by automatically restarting the node application when filing changes in the directory. and install the package before using it.

 

Leave a Comment

Your email address will not be published. Required fields are marked *