gpt4 book ai didi

javascript - 计算 Mongoose hook 内的平均值

转载 作者:行者123 更新时间:2023-11-27 23:59:18 25 4
gpt4 key购买 nike

我想在每次将新元素添加到集合中时计算平均值。基本上,我想要计算的是“预保存” Hook 内的内容,但我总是得到未定义的结果。

这是架构:

var CommentSchema = new Schema({
posted:{
type:Date,
default:Date.now
},
text:{
type: String
},
owner:{
_id:{
type: Schema.Types.ObjectId, ref: 'User'
},
displayName:{
type:String
}
},
reference: {
objectType:{
type: String,
enum: [ 'document','element','process', 'project', 'story']
},
_id:{
type: Schema.Types.ObjectId
}
},
sentiment:{
score:{
type:Number,
default:0.0
},
comparative:{
type:Number,
default:0.0
}
}
});

CommentSchema.pre('save', function(next){
var thiz = this;
// this code is inside another callback, that's the reason I'm using thiz
if(thiz.reference.objectType ==='element'){
mongoose.models['Comment'].aggregate([
{ $match:{'reference._id': mongoose.Types.ObjectId(thiz.reference._id)} },
{ $group:{'reference._id': mongoose.Types.ObjectId(thiz.reference._id), average:{$avg:'$sentiment.score'}}}
],
function(err, result){
console.log('------------------');
console.log('result',result);
console.log('------------------');
}
);
}
next();
});

我总是得到未定义的结果,但是,如果我像下面的示例一样查询,我会得到评论列表。

db.getCollection('comments').find({"reference._id":ObjectId("55a69276242aa1837a1ecb6c")})

我是否遗漏了什么?

最佳答案

{ $group: { _id: null, average: { $avg: '$sentiment.score' } } }

"The _id field is mandatory; however, you can specify an _id value of null to calculate accumulated values for all the input documents as a whole."

http://docs.mongodb.org/manual/reference/operator/aggregation/group/

$group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }

关于javascript - 计算 Mongoose hook 内的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31953210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com