0

I am currently learning how to use the lookup queries for joins but not getting the expected output

Schema 1

State
{
 state_name: { type: String, required: true },
 country_name: { type: String, required: true }
}

Schema 2

User
{
  name: { type: String },
  state: { type: Schema.Types.ObjectId, ref: 'State', required: true },
  createdAt: { type: Date, default: Date.now }
}

Query I tried

db.User.aggregate([
    { $match: { _id: ObjectId(b1b1b1) } },
    {
    $lookup: {
      localField: 'state',
      from: 'state',
      foreignField: '_id',
      as: 'user_info'
    }
  }, 
  ]).then(console.log)

Getting user_info as an empty array while I do have both documents like this

State
{
  _id: a1a1a1,//ObjectId
  state_name: "UP",
  country_name: "India"
}
User
{
   _id:b1b1b1,//ObjectId
   name: Test,
  state: a1a1a1,//ObjectId
  createdAt:"random date"
}

Output:

[{
_id:b1b1b1,//ObjectId
   name: Test,
  state: a1a1a1,
  createdAt:"random date",
userInfo:[]
}]
Raghu Chahar
  • 1,637
  • 2
  • 15
  • 33

0 Answers0