获取 MongoDB 和 Express 中产品评论的平均费率

Get average rate for product comments in MongoDB and Express

我想根据评论率计算产品的平均评分, 确切地说,当客户调用获取所有产品 api

时,我想 return 产品对象再添加一个 属性 作为响应

我的产品架构如下,在此先感谢您。

const mongoose = require("mongoose");
const { s, rs, n, rn, ref, rref } = require("../utils/mongo");

let commentSchema = new mongoose.Schema(
  {
    user: rref("user"),
    body: rs,
    rate: {
      ...n,
      default: 0,
      enum: [0, 1, 2, 3, 4, 5],
    },
  },
  { timestamps: true }
);

let schema = new mongoose.Schema(
  {
    user: rref("user"),
    name: rs,
    description: s,
    images: [s],
    price: rn,
    discount: n,
    sizes: [sizeSchema],
    categories: [ref("category")],
    tags: [s],
    comments: [commentSchema],
    rating: n,
    inStock: {
      type: Boolean,
      default: true,
    },
    stock: n,
    sold: {
      ...n,
      default: 0,
    },
    view: {
      ...n,
      default: 0,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("product", schema);

我想 return 作为这样的回应:

let result = [
 {
   name: 'product name', 
   comments: [
      {
        user: "2a2sdw22das5262123223",
        body: "good product",
        rate: 4
      },
      {
        user: "2a2sdw22das5262123223",
        body: "good product",
        rate: 2
      }
   ], 
   avgRate: 2, // how to calculate this?
   price: 20
   ...
 }
]

您可以使用聚合管道来执行此操作,它会添加 avgRating 字段 avgRate,您可以将其用于将来的参考:

db.collectionName.aggregate([{ $addFields : { avgRate: { $avg: "$comments.rate"} } }])