【问题标题】:Get average rate for product comments in MongoDB and Express在 MongoDB 和 Express 中获取产品评论的平均率
【发布时间】:2021-06-30 12:58:10
【问题描述】:

我想根据 cmets rate 计算产品的平均评分, 当客户端调用获取所有产品 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
   ...
 }
]

【问题讨论】:

    标签: node.js mongodb express aggregation-framework average


    【解决方案1】:

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

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

    【讨论】:

    • 没想到会这么简单,谢谢大佬的支持,我用$group试过了
    • 不客气,mongodb 确实提供了不同的运算符。您可以查看其文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多