MongoDB using ID to access all the data with virtual ID

Model File :

const mongoose = require("mongoose");

const productSchema = mongoose.Schema({
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  richDescription: {
    type: String,
    default: "",
  },
  image: {
    type: String,
    default: "",
  },

  brand: {
    type: String,
    default: "",
  },
  price: {
    type: Number,
    default: 0,
  },
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Category",
  },
  countInStock: {
    type: Number,
    required: true,
    min: 0,
    max: 255,
  },
  rating: {
    type: Number,
    default: 0,
  },
  numReviews: {
    type: Number,
    default: 0,
  },
  isFeatured: {
    type: Boolean,
    default: false,
  },
});

productSchema.virtual("id").get(function () {
    return this._id.toHexString();
});


productSchema.set('toJSON',{
    virtuals:true,
})

// exports.Categories=mongoose.model('Categories',categoriesSchema);
exports.Product = mongoose.model("Product", productSchema);


Router File

 

const express = require("express");
const router = express.Router();
const { Product } = require("../models/products");
const { Categories } = require("../models/categories");

router.get("/", async (req, res) => {
   
      const productList = await Product.find()
    //   .populate('category');
    //    .select('name image rating -_id');
      res.send(productList);
    if(!productList) {
      res.status(500).json({ success: false, error: error.message });
    }
  });


  router.get(`/:id`, async (req, res) => {
    try {
      const product = await Product.findById(req.params.id)
   
      if (!product) {
        res.status(404).json({ success: false, message: 'Product not found' });
      }
   
      res.send(product);
    } catch (error) {
      res.status(500).json({ success: false, message: 'Internal Server Error' });
    }
  });
 
 
router.post("/", async (req, res) => {
  try {
    const category = await Categories.findById(req.body.category);
    if (!category) {
      return res.status(400).send("Invalid category");
    }

    const product = new Product({
      name: req.body.name,
      description: req.body.description,
      richDescription: req.body.richDescription,
      image: req.body.image,
      brand: req.body.brand,
      price: req.body.price,
      category: req.body.category,
      countInStock: req.body.countInStock,
      rating: req.body.rating,
      numReviews: req.body.numReviews,
      isFeatured: req.body.isFeatured,
    });

    const savedProduct = await product.save();

    res.send(savedProduct);
  } catch (error) {
    res
      .status(500)
      .json({ error: "The product could not be created: " + error.message });
  }
});

router.put('/:id', async(req, res)=>{
 
  const product=await Product.findByIdAndUpdate(
      req.params.id,
      {
        name: req.body.name,
        description: req.body.description,
        richDescription: req.body.richDescription,
        image: req.body.image,
        brand: req.body.brand,
        price: req.body.price,
        category: req.body.category,
        countInStock: req.body.countInStock,
        rating: req.body.rating,
        numReviews: req.body.numReviews,
        isFeatured: req.body.isFeatured,  
      }
  )
  if(!product)
  return res.status(404).send('the product cannot be created!');

  res.send(product);
})





router.delete('/:id', async (req, res) => {
   
  try {

    const product = await Product.findByIdAndRemove(req.params.id);
    if (product) {
      return res.status(200).json({ success: true, message: 'The category is deleted now' });
    } else {
      return res.status(404).json({ success: false, message: 'Category not found' });
    }
  } catch (err) {
    return res.status(404).json({ success: false, error: err });
  }
});

 
router.get(`/get/count`, async (req, res) => {
  try {
    const productCount = await Product.countDocuments();
 
    if (productCount === 0) {
      res.status(404).json({ success: false, message: 'Product not found' });
    }
 
    res.send({ count: productCount });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Internal Server Error' });
  }
});



router.get(`/get/featured`, async(req,res) =>{
  const products=await Product.find({isFeatured:true})

  if(!products){
    res.status(500).json({success:false});
  }

  res.send(products);
})

router.get(`/get/featured/:count`, async(req,res) =>{
  const count =req.params.count ? req.params.count:0;
  const products=await Product.find({isFeatured:true}).limit(count);

  if(!products){
    res.status(500).json({success:false});
  }

  res.send(products);
})

module.exports = router;

Post a Comment

0 Comments