如何实现Review增删API及与Product的Mongoose虚拟填充?
实现Review模型API及与Product的虚拟填充关联
1. 完善Review Schema
首先补充关联产品的字段,修正ID生成逻辑,并配置虚拟关联规则:
import { v4 as uuidv4 } from "uuid"; import mongoose from "mongoose"; const Schema = mongoose.Schema; export const ReviewSchema = new Schema( { userId: { type: String, required: "Enter the userId", // 若允许用户对同一产品多次评论,需移除unique;若限制单用户单产品仅一条评论,建议添加userId+productId联合唯一索引 // unique: true, }, description: { type: String, required: "Enter your review", }, productId: { type: String, required: "Enter the product ID", ref: "Product" }, _id: { type: String, default: uuidv4, required: true, }, }, { timestamps: { createdAt: "cDate", updatedAt: "uDate", }, toJSON: { virtuals: true }, toObject: { virtuals: true } } ); // 给Review添加虚拟关联,指向所属产品 ReviewSchema.virtual('product', { ref: 'Product', localField: 'productId', foreignField: '_id', justOne: true });
2. 实现Review创建API
创建reviewController.js,编写添加评论的接口逻辑:
import mongoose from "mongoose"; import { ReviewSchema } from "../models/reviewModel"; const Review = mongoose.model("Review", ReviewSchema); // 创建评论API export const addNewReview = (req, res) => { const { userId, description, productId } = req.body; if (!userId || !description || !productId) { return res.status(400).json({ message: "缺少必填字段" }); } const newReview = new Review(req.body); newReview.save((err, review) => { if (err) { return res.status(500).send(err); } res.status(201).json(review); }); };
3. 实现Review删除API
在reviewController.js中继续添加删除评论的接口:
// 删除评论API export const deleteReview = (req, res) => { Review.deleteOne({ _id: req.params.reviewID }, (err) => { if (err) { return res.status(500).send(err); } res.json({ message: "评论删除成功" }); }); };
4. 给Product Schema添加虚拟填充关联
修改已有的Product Schema,添加虚拟字段关联该产品的所有评论:
import { v4 as uuidv4 } from "uuid"; import mongoose from "mongoose"; 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", }, toJSON: { virtuals: true }, toObject: { virtuals: true } } ); // 虚拟填充:关联该产品的所有评论 ProductSchema.virtual('reviews', { ref: 'Review', localField: '_id', foreignField: 'productId', justOne: false });
5. 更新Product详情API以返回关联评论
修改Product控制器中的详情接口,添加虚拟字段的填充逻辑:
export const getProductWithID = (req, res) => { Product.findById(req.params.productID) .populate('reviews') .exec((err, product) => { if (err) { return res.send(err); } res.json(product); }); };
内容的提问来源于stack exchange,提问作者hritik
相关产品推荐
相关产品推荐

