Node.js 使用Mongoose(MongoDB)实现addFields
我试图计算产品评级的平均值。而不是每次我们需要价值时计算产品的平均评级。每次有人给我评分时我都会计算。我希望在文档中看到其他字段,但出于某种原因,Node.js 使用Mongoose(MongoDB)实现addFields,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我试图计算产品评级的平均值。而不是每次我们需要价值时计算产品的平均评级。每次有人给我评分时我都会计算。我希望在文档中看到其他字段,但出于某种原因,console.log('stats:',stats)正在打印一个空数组,并且字段未添加到文档中。让我知道我做错了什么 const calculateAvgRating = async (id) => { try { const stats = await Product.aggregate([ { $match: { _
console.log('stats:',stats)
正在打印一个空数组,并且字段未添加到文档中。让我知道我做错了什么
const calculateAvgRating = async (id) => {
try {
const stats = await Product.aggregate([
{ $match: { _id: id } },
{
$addFields: {
avgRating: {
$avg: '$ratings.star',
},
nRatings: {
$size: '$ratings',
},
},
},
]);
console.log('stats: ', stats);
} catch (err) {
console.log(`calculateAvgRating error: ${err}`);
}
};
模式
import mongoose from 'mongoose';
const { ObjectId } = mongoose.Schema;
const ParentSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
required: true,
maxlength: 32,
text: true,
},
slug: {
type: String,
unique: true,
lowercase: true,
index: true,
},
price: {
type: Number,
required: true,
trim: true,
maxlength: 32,
},
quantity: Number,
ratings: [
{
star: Number,
postedBy: { type: ObjectId, ref: 'User' },
},
],
},
{
timestamps: true,
}
);
export default mongoose.models.Product ||
mongoose.model('Product', ParentSchema);
您的查询看起来不错,您需要在匹配阶段将输入的
id
从字符串转换为对象id{u id:mongoose.Types.ObjectId(id)}很遗憾没有更改。它会打印出结果,但文档中没有更改。可能您遗漏了什么,我看不到您的查询中有任何其他问题。只需确保inputid
的产品在集合中可用。聚合函数将只返回结果。如果您想修改文档,请考虑<代码> $合并<代码>阶段,或者使用<代码> UpDeTeON</代码>。