我正在构建要在aggregate()中执行的查询,如下所示:
query.$project = {};
query.$project.created_at = '$created_at';
query.$project.month = {};
query.$project.month.$month = currentMonth;
query.$match = {};
query.$match.month = currentMonth.getMonth() + 1;
query.$limit = 5;
query.$sort = {};
query.$sort.created_at = -1;
query.callback = function(err, result){
// do something
};
console.dir(query);
但是当我执行以下命令时:
DataTable.aggregate(query);
I get this:
Error: Arguments must be aggregate pipeline operators
at Aggregate.append (C:\myproject\node_modules\mongoose\lib\aggregate.js:87:11)
at new Aggregate (C:\myproject\node_modules\mongoose\lib\aggregate.js:47:17)
at Function.aggregate (C:\myproject\node_modules\mongoose\lib\model.js:1889:17)
at C:\myproject\app\routes.js:179:23
at C:\myproject\node_modules\async\lib\async.js:570:21
at C:\myproject\node_modules\async\lib\async.js:249:17
at C:\myproject\node_modules\async\lib\async.js:125:13
我现在有两个问题:
- 有没有更好的方法来构建此查询。
- 在这里如何指定回调函数。
编辑
我将上述代码修改如下:
query.$project = {};
query.$project.created_at = '$created_at';
query.$project.month = {};
query.$project.month.$month = currentMonth;
query.$match = {};
query.$match.month = currentMonth.getMonth() + 1;
query.$limit = 5;
query.$sort = {};
query.$sort.created_at = -1;
但是当我执行以下命令时:
DataTable.aggregate(query, function(err, result){
// do something
});
{$project:{},$match:{},$sort:{}}
,但这是不正确的。正确构建的查询对象应该是这样的:[{$project:{}},{$match:{}}]
,就像 @thefourtheye 的回答所提到的那样。 - BatScream