Teo*_*dor 1 javascript mongoose mongodb node.js express
您好我在Robomongo中执行的以下查询按预期工作:
db.av.group(
{
key: { roomId: 1},
cond: { dateOfDay: { $gte: new Date('12/01/2014'), $lt: new Date('12/30/2014') } },
reduce: function( curr, result ) {
result.total += curr.price;
result.count++;
},
initial: { total : 0,
count : 0
},
finalize: function(result) {
result.avg = Math.round(result.total / result.count);
}
}
)
Run Code Online (Sandbox Code Playgroud)
在快递应用程序中实现之后:
app.get('/api/checkAv/:checkIn/:checkOut', function(req, res) {
var checkIn = req.params.checkIn,
checkOut = req.params.checkOut,
roomType = req.params.roomType;
model.Av.group(
{
key: { roomId: 1},
cond: { dateOfDay: { $gte: new Date('12/01/2014'), $lt: new Date('12/30/2014') } },
reduce: function( curr, result ) {
result.total += curr.price;
result.count++;
},
initial: { total : 0,
count : 0
},
finalize: function(result) {
result.avg = Math.round(result.total / result.count);
}
}
).exec(function(err, av) {
if (err)
res.send(err);
res.json(av);
});
});
Run Code Online (Sandbox Code Playgroud)
我上了控制台:
TypeError:对象函数模型(doc,fields,skipId){if(!(this instanceof model))返回新模型(doc,fields,skipId); Model.call(this,doc,fields,skipId); 在/home/www/domain.com/api/routes/routes.js:58:18没有方法'group'在Layer.handle [as handle_request](/home/www/domain.com/node_modules/express/ lib/router/layer.js:82:5)
at Route.dispatch下一步(/home/www/domain.com/node_modules/express/lib/router/route.js:100:13)(/ home/www/domain.com/node_modules/express/lib/router/route.js:81:3)
在Layer.handle [as handle_request](/home/www/ domain.com/ node_modules/express/lib/router/layer.js: 82:5)
在/home/www/brasovapartments.com/node_modules/express/lib/router/index.js:234:24 at param(/home/www/domain.com/node_modules/express/lib/router/index .js:331:14)在param(/home/www/domain.com/node_modules/express/lib/router/index.js:347:14)param(/home/www/domain.com/node_modules/express) /lib/router/index.js:347:14)在Function.proto.process_params(/home/www/domain.com/node_modules/express/lib/router/index.js:391:3)
现在阅读我看到有些人定义了一个组属性但不确定Mongoose模式中的方式和位置?你能不能给我一个暗示我的问题是什么?
groupMongoose不支持该命令,并且在MongoDB 3.4中也不推荐使用该命令,因为使用它可以更好地提供其功能aggregate.
您可以使用以下内容执行此aggregate操作:
model.Av.aggregate([
{$match: {dateOfDay: {$gte: new Date('12/01/2014'), $lt:new Date('12/30/2014')}}},
{$group: {
_id: '$roomId',
total: {$sum: '$price'},
count: {$sum: 1},
avg: {$avg: '$price'}
}}
], function (err, result) {...});
Run Code Online (Sandbox Code Playgroud)
如果您不需要,可以省略total和count字段,因为$avg操作员可以直接计算平均价格.
| 归档时间: |
|
| 查看次数: |
9310 次 |
| 最近记录: |