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

guz6ccqo  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(130)

我想根据评论率计算产品的平均评分,确切地说,我想在客户端调用获取所有产品API时返回带有多一个属性的产品对象作为响应
我产品方案如下,提前谢谢。

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);

我想返回这样的内容作为回应:

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
   ...
 }
]
bq3bfh9z

bq3bfh9z1#

您可以使用聚合管道来完成此操作,它将添加avgRating字段avgRate,您可以将其用于将来的引用:

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

相关问题