Search code examples
mongodbexpressmongodb-querymonk

Monk / Mongodb performing find inside callback of another find


I have the following document structure to record a user's friends list:

{ 
    "_id" : ObjectId("5df4d0ac6480078812e7b2ff"), 
    "name" : "Alice"
    "friends" : [ "Bob", "John" ] 
}

When receiving a request for a user, say "Alice", I'd like to retrieve Alice's friends as well as their _id field, returning a response of an array of friends' names and their _id, e.g.

[{"name": "Bob", "_id": "abcdef"}, {"name": "John", "_id": "ghjikl"}

How do I go about doing this in Monk?

My idea was to use collection.find() on the user to retrieve the friends list, then loop through it to perform another find() to get their _id. But that doesn't work as I can't update variables from outside the nested find() callback function.


Solution

  • This aggregation will gives you something close to what you want:

    db.users.aggregate([
      {
        "$match": {
          "name": "Alice"
        }
      },
      {
        "$lookup": {
          "from": "users",
          "as": "friends",
          "localField": "friends",
          "foreignField": "name"
        }
      },
      {
        "$project": {
          "_id": 0,
          "friends._id": 1,
          "friends.name": 1,
    
        }
      }
    ])
    

    Output:

    [
      {
        "friends": [
          {
            "_id": "abcdef",
            "name": "Bob"
          },
          {
            "_id": "ghjikl",
            "name": "John"
          }
        ]
      }
    ]