Search code examples
mongodblookuppopulatemongoose-populate

lookup with conditional localField


StaffOneToOne.aggregate([
  {"$match": {$or: [{ fromStaffId: req.user._id }, { toStaffId: req.user._id }]}},
  {$cond:{
    if:{fromStaffId:req.user._id},
    then:{$lookup: {
      from: 'pharmacists',
      localField: 'fromStaffId',
      foreignField: '_id',
      as: 'p_list'
    }},
    else:{$lookup: {
      from: 'pharmacists',
      localField: 'fromStaffId',
      foreignField: '_id',
      as: 'p_list'}}
  }}
])
{
    "_id" : ObjectId("6310901b86c6077c5d3be84f"),
    "message" : "Hello Hau",
    "date" : 1662029851620.0,
    "messageType" : 0,
    "staffType" : 0,
    "isSeen" : 0,
    "image" : "",
    "toStaffId" : ObjectId("60c8908ef1c80777f6c78460"),
    "fromStaffId" : ObjectId("608599c361480b4cc2dd4946"),
    "sentBy" : ObjectId("608599c361480b4cc2dd4946"),
    "createdAt" : ISODate("2022-09-01T10:57:31.902Z"),
    "updatedAt" : ISODate("2022-09-01T10:57:31.902Z"),
    "__v" : 0
}

I am trying to populate fromStaffId and toStaffId with lookup but in my case when my id matches with fromStaffId then i have to populate toStaffId and vice versa i am trying to put conditional lookup which is not working my code is


Solution

  • You can set a field with this value:

    db.StaffOneToOne.aggregate([
      {$match: {$or: [{fromStaffId: req.user._id}, {toStaffId: req.user._id}]}},
      {$addFields: {
          localField: {
            $cond: [
              {$eq: ["$fromStaffId", req.user._id]},
              "$toStaffId",
              "$fromStaffId"
            ]
          }
        }
      },
      {$lookup: {
          from: "pharmacists",
          localField: "localField",
          foreignField: "_id",
          as: "p_list"
        }
      }
    ])
    

    See how it works on the playground example