使用Mongoose $avg算平均值报错arguments must be aggregate pipeline operators如何解决
报错原因
- 聚合管道格式不符合语法要求:MongoDB聚合管道的每个操作阶段($match、$group等)都需要是数组中独立的对象,你将$match和$group两个操作符写在了同一个对象里,触发了参数校验报错。
- 存在两处拼写错误:一是聚合方法名写为了
aggragate,Mongoose正确的聚合方法拼写为aggregate;二是钩子中调用的方法名写为了getAvarageCost,和你定义的静态方法名getAverageCost不一致。
修复方案
首先修正聚合逻辑的拼写和管道结构:
//static method to get avg of course tuitions CourseSchema.statics.getAverageCost = async function (bootcampId) { console.log('calculating avg cost... with bootcampId:' + bootcampId); const obj = await this.aggregate([ // 拆分$match为独立的阶段对象 { $match: { bootcamp: bootcampId } }, // 拆分$group为独立的阶段对象 { $group: { _id: '$bootcamp', averageCost: { $avg: '$tuition' } } } ]); console.log(obj); }
再修正钩子中的方法名拼写:
// Call getAverageCost after save CourseSchema.post('save', function () { this.constructor.getAverageCost(this.bootcamp); }) // Call getAverageCost after remove CourseSchema.post('remove', function () { this.constructor.getAverageCost(this.bootcamp); })
内容的提问来源于stack exchange,提问作者Batalin Vlad
相关产品推荐
相关产品推荐

