Home > Software engineering >  lookup with conditional localField
lookup with conditional localField

Time:09-07

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

CodePudding user response:

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

  • Related