$unwind 嵌套文档和 $match

$unwind nested document and $match

我有一个嵌套文档,如下所示:

    var User = new Schema({
    id: String,
    position: [{
        title: String,
           applied:[{
                candidate_id: String,
                name: String
        }],
        }],

我想要做的是 return 所有 'applied' 匹配特定 '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'});
});

我有另一个函数,它 return 匹配所有位置,并且该代码有效:

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 个申请的候选人,我需要做的是 return 如果匹配 mongoose 查询的嵌套对象。

你的代码对我来说似乎很好我已经实现了同样的并且它对我有用唯一可能的问题可能是你的 position="58dc2bd4e7208a3ea143959e" 它可能正在谈论它作为一个字符串只需使用以下代码将其转换为 objectId 并检查它是否适合您。

var mongoose = require('mongoose');

     var position = mongoose.Types.ObjectId("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'});
        });