top of page

Performing CRUD operations against MongoDB in Node.js REST API with Express & Mongoose

Writer's picture: CODING Z2MCODING Z2M

Updated: May 3, 2023


What is Mongoose & uses of defining a model using Mongoose schema in Node.js

Mongoose is an Object Data Modeling (ODM) library for Node.js and MongoDB, which provides a higher-level abstraction for working with MongoDB. Mongoose allows developers to define schemas for their MongoDB collections, which provides a way to enforce data consistency and validation rules.

Here are some uses of defining a model using Mongoose schema in Node.js:

  1. Data consistency: Defining a schema for your MongoDB collection helps ensure that your data is consistent across all documents. You can define the structure of your documents and specify data types for each field. This helps prevent data entry errors and ensures that your application can work with the data in a consistent manner.

  2. Validation: Mongoose provides built-in validation options that allow you to define rules for the data that is being entered into your MongoDB collection. You can define validation rules such as required fields, minimum and maximum values, and regular expressions. This helps ensure that your data meets specific criteria before being saved to the database.

  3. Middleware: Mongoose also provides middleware functions that allow you to run code before or after certain operations. For example, you can define middleware that is triggered before a document is saved to the database or after a document is retrieved from the database. This provides a way to perform additional operations or modifications on your data.

  4. Querying: Mongoose provides a powerful querying API that allows you to easily search for and retrieve data from your MongoDB collection. You can use methods like find(), findOne(), and aggregate() to retrieve data based on specific criteria.

  5. Relationships: Mongoose allows you to define relationships between collections using references or sub-documents. This provides a way to link related data across different collections and allows you to perform operations on related data.

Overall, using Mongoose schema to define a model provides a way to structure your data and add validation, middleware, and querying capabilities to your MongoDB collections, which helps make your Node.js application more robust and scalable.

Perform CRUD operations against MongoDB in Node.js REST API using Mongoose

To connect and perform CRUD operations against MongoDB in Node.js REST API with Express by modeling Product using Mongoose, follow these steps:

1. Installing mongoose by running npm i mongoose

2. Create a database and a collection in MongoDB cluster

3. Connect App with MongoDB Cluster:

Note: In your Mongo DB Cluster, choose "Add your connection string into your application code" option copy the connection string and add it in the .env file


4. Connect to the MongoDB database using Mongoose: Create a db connection method in the file dbConnection.js of 'config' folder for database connection configuration as shown below and call the connection method in the server.js


​const mongoose = require ("mongoose");

const connectDb = async () => {
    try {
        const connect = await mongoose.connect(process.env.CONNECTION_STRING);
        console.log("DB Connected", connect.connection.host, connect.connection.name);
    } catch(err) {
        console.log(err);
        process.exit(1);
    }
};

module.exports = connectDb;

5. Create a schema for the Product model using Mongoose & Create a model for the Product using the schema:


​const mongoose = require("mongoose");

const productSchema = mongoose.Schema({
    title:{
        type:String,
        required: [true, "Title can't be null"]
    },
    desc:{
        type:String,
        required: [true, "Description can't be null"]
    },
    price:{
        type:Number,
        required: [true, "Price can't be null"]
    },
    stock:{
        type:Number,
        required: [true, "Stock can't be null"]
    }
}, {
    timestamps: true,
})

module.exports = mongoose.model("Product", productSchema);

6. Create ProductController.js Create a route for creating a new product, getting all products and so on.


​const asyncHandler = require("express-async-handler");
const Product = require("../models/ProductModel");

//@desc Get all Products
//@route GET /api/products
//@access private
const getProducts = asyncHandler(async (req, res) => {
  const products = await Product.find();
  res.status(200).json(products);
  });


//@desc Create new Product
//@route POST /api/products
//@access private
const createProduct = asyncHandler(async (req, res) => {
  const {title, desc, price, stock} = req.body;
  if(!title || !desc || !price || !stock) {
   res.status(400);
   throw new Error("All Fileds Are Mandatory!");
  }
   const product = await Product.create({
     title,
     desc,
     price,
     stock,
   })
   res.status(200).json(product);
   });
   
   //@desc Get Product
//@route GET /api/products/:id
//@access private
const getProduct = asyncHandler(async (req, res) => {
  const product = await Product.findById(req.params.id);
  if(!product){
    res.status(404);
    throw new Error("Product Not Found!");
  }
    res.status(200).json(product);
    });
   
   module.exports= { getProducts, 
    createProduct, 
    getProduct, 
    updateProduct, 
    deleteProduct};

35 views0 comments

Comments


Join us today and take the first step towards advancing your IT career!

More codingZ2M

Never miss an update

Thanks for submitting!

bottom of page