Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/407.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 计算猫鼬钩内的平均值_Javascript_Mongodb_Mongoose - Fatal编程技术网

Javascript 计算猫鼬钩内的平均值

Javascript 计算猫鼬钩内的平均值,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,我想计算每次向集合添加新元素时的平均值。基本上,我试图计算的是一个“预保存”钩子,但我总是得到未定义的结果 这是模式: var CommentSchema = new Schema({ posted:{ type:Date, default:Date.now }, text:{ type: String }, owner:{ _id:{ type: S

我想计算每次向集合添加新元素时的平均值。基本上,我试图计算的是一个“预保存”钩子,但我总是得到未定义的结果

这是模式:

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' } } }
_id字段是必需的;但是,您可以指定_id值为 null以计算所有输入文档的累积值作为 全部。”

$group:{u id:,:{:},…}

我明白了,我只需要按_id分组,而不是引用包含id的“列”,谢谢你的提示!
$group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }