Tuesday, June 14, 2016

Mongoose $lookup aggregate

Not sure why $match has to be first, also parm has to be converted to number
from is the out side collection, foreignField is also from out side collection. "as" defines name of the result array name.  LocalField is the base collection.

router.get('/person_narrative/person_id/:person_id', function (req, res, next) {
 
  KMPersonNarrative.aggregate([
      {
        $match: {
          person_id: Number(req.params.person_id)
        }
      },
      {
        $lookup: {
          from: "ror_narratives",
          localField: "narrative_id",
          foreignField: "id",
          as: "texts"        }
      }

    ])
    .exec()
    .then(function (allNarratives) {
      res.json(allNarratives);
    });
});

No comments:

Post a Comment