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---
- Create review
- Delete review and how to virtually populate the reviews.**