Home > other >  MongoDb find all objects that contain nested value
MongoDb find all objects that contain nested value

Time:03-02

This is my user object sent as token in req:

{
    "_id": "6212aba16653621e67393549c",
    "name": "User",
    "email": "[email protected]",
    "__v": 0
}

This is my get function code:

const getSharedLists = asyncHandler(async (req, res) => {
  const lists = await List.find({
    sharedWith: { email: req.user.email },
  });

  res.status(200).json(lists);
});

This is what object looks like:

{
    "_id": "621817233300dfff68e23710",
    "user": "6212ab33383621e67393549c",
    "listName": "test update",
    "private": true,
    "items": [
        {
            "itemName": "Bananas",
            "quantity": 3,
            "isBought": false,
            "isle": "isle",
            "_id": "621b043622147906eece2e72"
        },
    ],
    "sharedWith": [
        {
            "email": "[email protected]",
            "_id": "621bdbf0791a322534284c49"
        }
    ],
    "createdAt": "2022-02-24T23:39:25.668Z",
    "updatedAt": "2022-02-27T21:21:03.584Z",
    "__v": 0,
},

I keep getting empty array back, even when hard code req.user.email as "[email protected]" for example. I need to find all lists on MongoDb that have my email in array of sharedWith.

Can somebody help please. Apparently I'm using List.find method wrong but can't seem to figure out the syntax.

CodePudding user response:

You need (.) dot notation.

const lists = await List.find({
  "sharedWith.email" : req.user.email
});

Sample Mongo Playground


Reference

Specify a Query Condition on a Field Embedded in an Array of Documents

  • Related