Sunday, 2 April 2017

$unwind nested document and $match

I have a nested document which looks like:

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

What I am looking to do is return all of the 'applied' subdocuments which match a certain 'candidate_id'

What I have so far:

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

I have another function which returns all the positions that match, and that code works:

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

So basically I am struggling with getting a sub-sub-document. Any idea where I'm going wrong?



via user

No comments:

Post a Comment