【发布时间】:2017-08-27 09:26:21
【问题描述】:
我有一个嵌套文档,如下所示:
var User = new Schema({
id: String,
position: [{
title: String,
applied:[{
candidate_id: String,
name: String
}],
}],
我要做的是返回与某个“candidate_id”匹配的所有“应用”子文档
到目前为止我所拥有的:
app.get('/applied', function(req, res){
var position = "58dc2bd4e7208a3ea143959e";
User.aggregate(
{$unwind : "$position"},
{$unwind : "$position.applied"},
{$match:{'position.applied.candidate_id': position}}).exec(function (err, result) {
console.log(result);
});
res.render('applied', { title: 'applied',layout:'candidate'});
});
我有另一个函数,它返回所有匹配的位置,并且该代码有效:
app.post('/search', function (req, res) {
var position = new RegExp(req.body.position, 'i');
var location = new RegExp(req.body.location, 'i');
User.aggregate(
{$unwind : "$position"},
{$match:{'position.title': position,'position.location':location}}).exec(function (err, result) {
console.log(result);
res.send({ results: result });
});
});
所以基本上我正在努力获取子子文档。知道我哪里出错了吗?
样本数据:
{
"_id" : ObjectId("58c2871414cd3d209abf5fc9"),
"position" : [
{
"_id" : ObjectId("58d6b7e11e793c9a506ffe8f"),
"title" : "Software Engineer",
"applied" : [
{
"candidate_id" : "58d153e97e3317291gd80087",
"name" : "Sample user"
},
{
"candidate_id" : "58d153e97e3317291fd99001",
"name" : "Sample User2"
}
]
},
{
"_id" : ObjectId("58c2871414cd3d209abf5fc0"),
"title" : "Software Engineer",
}
],
}
上面发生的情况是有 2 个职位,其中一个(第一个条目)有 2 个已申请的候选人,我需要做的是返回嵌套对象,如果它与 mongoose 查询匹配。
【问题讨论】:
-
发生了什么?您还有一些无法正常工作的示例数据吗?
-
@ExplosionPills 数组返回为空。我将更新问题以显示一些示例数据!
标签: node.js mongodb mongoose nested-queries subdocument