How to virtually populate the reviews?

Viewed 31

I am creating an app. Task is to create two models- Product and reviews on Product I have created Schema for Product and implement all apis(add product, read product, read product by id, update product and delete product) Now, how to create apis for review(create review and delete review) and virtually populate the reviews.

How to integrate these reviews with my product.

Product Schema---

import { v4 as uuidv4 } from "uuid";
import mongoose from "mongoose";
import { UUID } from "bson";

uuidv4();

const Schema = mongoose.Schema;

export const ProductSchema = new Schema(
  {
    name: {
      type: String,
      required: "Enter the name of product",
    },
    price: {
      type: Number,
      required: "Enter the price of product",
    },
    _id: {
      type: String,
      default: uuidv4,
    },
  },
  {
    timestamps: {
      createdAt: "cDate",
      updatedAt: "uDate",
    },
  }
);

Product APIs -

import mongoose from "mongoose";
import { ProductSchema } from "../models/productModel";

const Product = mongoose.model("Product", ProductSchema);

export const addNewProduct = (req, res) => {
  let newProduct = new Product(req.body);

  newProduct.save((err, product) => {
    if (err) {
      res.send(err);
    }
    res.json(product);
  });
};

export const getProducts = (req, res) => {
  Product.find({}, (err, product) => {
    if (err) {
      res.send(err);
    }
    res.json(product);
  });
};

export const getProductWithID = (req, res) => {
  Product.findById(req.params.productID, (err, product) => {
    if (err) {
      res.send(err);
    }
    res.json(product);
  });
};

export const updateProduct = (req, res) => {
  Product.findOneAndUpdate(
    { _id: req.params.productID },
    req.body,
    { new: true, useFindAndModify: false },
    (err, product) => {
      if (err) {
        res.send(err);
      }
      res.json(product);
    }
  );
};

export const deleteProduct = (req, res) => {
  Product.deleteOne({ _id: req.params.productID }, (err, product) => {
    if (err) {
      res.send(err);
    }
    res.json({ message: "successfully deleted product" });
  });
};

export default Product;

Reviews model-

import uuidv4 from "uuid/v4";
import mongoose from "mongoose";
import { UUID } from "bson";

const Schema = mongoose.Schema;

export const ReviewSchema = new Schema(
  {
    userId: {
      type: String,
      required: "Enter the userId",
      unique: true,
    },
    description: {
      type: String,
      required: "Enter your review",
    },
    _id: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: {
      createdAt: "cDate",
      updatedAt: "uDate",
    },
  }
);

**I want to create two apis---

  1. Create review
  2. Delete review and how to virtually populate the reviews.**
1 Answers
  • You need to add the product ID to the reviews model.
import uuidv4 from "uuid/v4";
import mongoose from "mongoose";
import { UUID } from "bson";

const Schema = mongoose.Schema;

export const ReviewSchema = new Schema(
  {
    userId: {
      type: String,
      required: "Enter the userId",
      unique: true,
    },
    productId: {
      type: String,
      required: "your preferred text",
      ref: "Product"
    },
    description: {
      type: String,
      required: "Enter your review",
    },
    _id: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: {
      createdAt: "cDate",
      updatedAt: "uDate",
    },
  }
);
  • Create Review API - productId should be sent in the body
export const addNewReview = (req, res) => {
  const newReview = new Review(req.body);

  newReview.save((err, review) => {
    if (err) {
      res.send(err);
    }
    res.json(review);
  });
};
  • Delete Review API
export const deleteReview = (req, res) => {
  Review.deleteOne({ _id: req.params.reviewID }, (err, review) => {
    if (err) {
      res.send(err);
    }
    res.json({ message: "successfully deleted review" });
  });
};
  • Now to virtually populate the reviews you need to adjust how you export and import the product model (It's preferred if you adjust it in the rest of the models as well)
import { v4 as uuidv4 } from "uuid";
import mongoose from "mongoose";
import { UUID } from "bson";

uuidv4();

const Schema = mongoose.Schema;

const ProductSchema = new Schema(
  {
    name: {
      type: String,
      required: "Enter the name of product",
    },
    price: {
      type: Number,
      required: "Enter the price of product",
    },
    _id: {
      type: String,
      default: uuidv4,
    },
  },
  {
    timestamps: {
      createdAt: "cDate",
      updatedAt: "uDate",
    },
  }
);

ProductSchema.virtual('reviews', {
    ref: 'Review',
    localField: '_id',
    foreignField: 'productId',
});

/* mongoose will not include virtuals by default - https://mongoosejs.com/docs/guide.html#virtuals */
ProductSchema.set('toObject', { virtuals: true });
ProductSchema.set('toJSON', { virtuals: true });

module.exports = mongoose.model('Product', ProductSchema);
  • Then you need to import it like this in the Product APIs file
import Product from "../models/productModel";
Related