gpt4 book ai didi

javascript - node.js/express 路由中的 Mongoose 组查询

转载 作者:行者123 更新时间:2023-11-30 07:23:44 25 4
gpt4 key购买 nike

您好,我有以下在 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);
}

}
)

在 express 应用中实现后:

 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);
});
});

我进入控制台:

TypeError: Object function model(doc, fields, skipId) { if (!(this instanceof model)) return new model(doc, fields, skipId); Model.call(this, doc, fields, skipId); } has no method 'group' at /home/www/domain.com/api/routes/routes.js:58:18 at Layer.handle [as handle_request] (/home/www/domain.com/node_modules/express/lib/router/layer.js:82:5)
at next (/home/www/domain.com/node_modules/express/lib/router/route.js:100:13) at Route.dispatch (/home/www/domain.com/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/home/www/domain.com/node_modules/express/lib/router/layer.js:82:5)
at /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) at param (/home/www/domain.com/node_modules/express/lib/router/index.js:347:14) at param (/home/www/domain.com/node_modules/express/lib/router/index.js:347:14) at Function.proto.process_params (/home/www/domain.com/node_modules/express/lib/router/index.js:391:3)

现在阅读周围我看到一些人定义了一个组属性,但不确定如何以及在 Mongoose 模式中的位置..?你能告诉我我的问题是什么吗?

最佳答案

group命令不受 Mongoose 支持,并且在 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) {...});

如果您不需要 totalcount 字段,则可以省略它们,因为 $avg运算符可让您直接计算平均价格。

关于javascript - node.js/express 路由中的 Mongoose 组查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26800740/

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