我正在使用带有mongoose插件的node.js来构建具有任务的简单应用程序。我的mongoDB架构如下所示:
var userSchema = mongoose.Schema({
username: String,
email : String,
password : String,
tasks: [{
title: String,
description: String,
date: {type: Array, "default":[]},
currentPeriod: Number,
periodQuantity: Number,
done: Boolean
}]
});
我想要做的是(例如)获取任务,其中“done”变量设置为true,并且是一个用户(同一文档)的一部分。目前,我的查询如下所示:
User.aggregate({$match:{'email':req.user.email}},{$unwind:"$tasks"},{$match:{'tasks.done':true}},{$project:{'tasks':1,'_id':0}}, function(err,tasks){
if (err) {
console.log('Something went wrong during getting inactive task(s) for user "' + req.user.email + '": ' + err);
res.send(err);
}
console.log('Succesfully got ' + tasks.length + ' inactive task(s) for user: "' + req.user.email + '".');
res.json(tasks);
});
问题是这种查询的结果是这样的
[
{"tasks":{"_id":"57372ef07329d9d8f2921ede","title":"Done1","description":"Done1Desc","currentPeriod":3,"periodQuantity":3,"done":true}},
{"tasks":{"_id":"57372ef07329d9d8f2921edf","title":"Done2","description":"Done2Desc","currentPeriod":11,"periodQuantity":11,"done":true}},
{"tasks":{"_id":"57372ef07329d9d8f2921ee3","title":"Done3","description":"Done3Desc","currentPeriod":3,"periodQuantity":3,"done":true}},
{"tasks":{"_id":"57372ef07329d9d8f2921ee4","title":"Done4","description":"Done4Desc","currentPeriod":4,"periodQuantity":4,"done":true}}
]
虽然我只想要“属性”任务的值。我设法使用
获得了我对mongo控制台感兴趣的结果> var results = [];
> db.users.aggregate({$match:{'email':'admin'}},{$unwind:"$tasks"},{$match:{'tasks.done':true}},{$project:{'tasks':1,'_id':0}}).forEach(function(u) {results.push(u.tasks)})
> results
[
{
"_id" : ObjectId("57372ef07329d9d8f2921ede"),
"title" : "Done1",
"description" : "Done1Desc",
"currentPeriod" : 3,
"periodQuantity" : 3,
"done" : true
},
{
"_id" : ObjectId("57372ef07329d9d8f2921edf"),
"title" : "Done2",
"description" : "Done2Desc",
"currentPeriod" : 11,
"periodQuantity" : 11,
"done" : true
},
{
"_id" : ObjectId("57372ef07329d9d8f2921ee3"),
"title" : "Done3",
"description" : "Done3Desc",
"currentPeriod" : 3,
"periodQuantity" : 3,
"done" : true
},
{
"_id" : ObjectId("57372ef07329d9d8f2921ee4"),
"title" : "Done4",
"description" : "Done4Desc",
"currentPeriod" : 4,
"periodQuantity" : 4,
"done" : true
}
]
>
我尝试使用foreach和每个函数在第二个代码段的末尾,但是当我这样做时,我收到错误
TypeError: User.aggregate(...).forEach is not a function