I have just started working on mongodb and I want to get data from foreign table(User) and table(Connection) by performing join but foreign table data is always an empty array
User Schema:
[
{key: 1, name: "a"},
{key: 2, name: "b"},
{key: 1, name: "c"},
{key: 2, name: "d"},
]
Connection schema:
[
{initiator_id: 1, target_id: 2}
{initiator_id: 3, target_id: 4}
]
And this is my join code
const pipeline = [
{
$match: {
initiator_id: { $eq: user_id },
},
},
{
$lookup: {
from: "user",
localField: "initiator_id",
foreignField: "key",
as: "user",
},
},
];
mongoose.model("connection").aggregate(pipeline).then((res) => {
console.log(res);
});
And the console.log response is an array in which the user field is always an empty array
[
{
connection_id: 'some_id'
initiator_id: 1
target_id: 2,
user: []//this is where I'm expecting data from User table but it is always empty
}
]
initiator_id, target_id, and key .... all are type Number