Search code examples
node.jsmongoosefindmongoose-schema

Mongoose: deep search


I have a schema whose returns is below:

"_id": "61d4791786dbde4bb0ecd622",
"members": [
    {
        "score": 75,
        "_id": "61d4791886dbde4bb0ece492",
        "userId": "60df085d4729322a7464babc",
        "penalties": [
            {
                "_id": "61d4791886dbde4bb0ece493",
                "penaltyScore": -10
            },
            {
                "_id": "61d4791886dbde4bb0ece494",
                "penaltyScore": -15
            }
        ]
    },
]

I want to find the register by userId. I tried to use:

ManeuverStatistics.find(userId && { members: { $in: userId } }).exec(
    (err, data) => {
      if (err) {
        res.status(500).send({ message: "failed!" });
        return;
      }
      res.status(200).send(data);
    }
  );

But it did not work... How can I make a deep search to find content that matches with the userId inside the members array?


Solution

  • I spent some hours trying to solve it, but I found a possible solution. To help any other programmer, here it's my approach:

    ManeuverStatistics.find(userId && { "members.userId": userId }).exec(
      (err, data) => {
        if (err) {
          res.status(500).send({ message: "failed!" });
          return;
        }
        res.status(200).send(data);
      }
    );
    

    Basically, I could access the key userId inside the object using members.userId.