MongoDB trying to marge two tables by id - cant make this

Viewed 39

I have two tables in my database.

teams table:

[
  {
    "users": [
      { "id": '5f9971e6f4f60959c0668896', "role": 'admin' },
      { "id": '5fb11570ece5672ba95850ee', "role": 'read' }
    ],
    "_id": '5fb0f993795d1634d4e486dc',
    "name": 'team1'
  },
  {
    "users": [
      { "id": '5fb11570ece5672ba95850ee', "role": 'admin' }
    ],
    "_id": "5fb0f993795d1634d4e48fed",
    "name": 'team2'
   }
]

users table:

[
 {
  "_id" : ObjectId("5f9971e6f4f60959c0668896"),
    "firstname" : "foo",
    "lastname" : "bar"
  },
  {
  "_id" : ObjectId("5fb11570ece5672ba95850ee"),
    "firstname" : "hey",
    "lastname" : "you"
  },
  {
  "_id" : ObjectId("5fb11570ece5672ba95grs0"),
    "firstname" : "12",
    "lastname" : "34"
  }
]

and what i want to get is this:

{
 users: 
  [
    { id: '5f9971e6f4f60959c0668896',firstname: "foo",lastname: "bar", role: 'admin' },
    { id: '5fb11570ece5672ba95850ee',firstname: "hey",lastname: "you", role: 'read' }
  ],
  _id: 5fb0f993795d1634d4e486dc,
  name: 'team1'
}

i'm trying to solve this a week and i didn't find solution.

Teams.aggregate([
            {
              $lookup: {
                from: "users",
                localField: "_id",
                foreignField: "users.id",
                as: "users",
              },
            },
          ]).then((data) => {
            console.log("data", data);
          });

tnx for the help

1 Answers

Your teams collection users.id need to be also ObjectId , not a string ... , or alternatively you need to change the users collection _id's to strings ...

Related