Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

Mongoose compare with a third level nested field value


I have the following collections: enter image description here

and I would like to do a find from collection1 all the way to collection 3 and 4 to compare name in one query.

example:

collection1.find({
    collection2.collection3.name: req.body.name3,
    collection2.collection4.name: req.body.name4
}).exec()

Solution

  • You need to use lookup, unwind and match, here is untested solution of your problem

     Model.aggregate([
         {
             $match: {
                 _id: req.params.id
                 // for object id use
                 // _id: mongoose.Types.ObjectId(req.params.id)
             }
         },
            {
              $lookup: {
                from: "collection2",
                localField: "collection2",
                foreignField: "_id",
                as: "Collection2"
              }
            },
            {
                $unwind: "$ColelctionTwo"
            },
            {
              $lookup: {
                from: "collection3",
                localField: "CollectionTwo.collection3",
                foreignField: "_id",
                as: "Collection3"
              }
            },
            {
              $lookup: {
                from: "collection4",
                localField: "CollectionTwo.collection4",
                foreignField: "_id",
                as: "Collection4"
              }
            }
          ]).exec(function(err, result) {
              if(err) {
                  // handle here
              }
              if(result) {
                  // do something here...
              }
          }