Search code examples
mongodbloopback

Link a model with 'hasMany' to a model with an array


I have 2 simple models:

    Person:
     - id: "1234"
     - name: "John"

    Jobs:
     - title: "Programmer"
     - personList:[{
         - personId: "1234"
         - personName: "John"
       },
       {
         ... another person
       }]

In short, I want to run this simple query:

    http://example.com/person?filter={"include":"jobs"}

So I can link the Person model to Jobs model and simply get all the person jobs too.

Normally, you would do that with a hasMany relation, but how to achieve that if its an array of objects?


Solution

  • You can use the below aggregation pipeline to $lookup jobs collection and return the matching jobs

    In mongo 3.6 and above

    db.person.aggregate([
        {$lookup : {
            from : "jobs", 
            let : {"personId" : "$id"}, 
            pipeline : [
                {$match : {"$expr" : {$in : ["$$personId", "$personList.personId"]}}},
                {$addFields : {personList : {$filter : {input : "$personList", as : "p", cond : {$eq : ["$$personId", "$$p.personId"]}}}}}
            ],
            as : "jobs"
        }}
    ]).pretty()