Conditional sort in MongoDB

Viewed 107

I'm working on a sort method in Nodejs/Mongoose with some sort params and now I need to add another one sorting by a recently added boolean property. Which means not every user has it.

In this Opportunity, I need to show first users in the compatibleProfessionals array which personalData.isUserPCD is true, then sort these users by their userAdherence (Integer) and finally sort everyone else by userAdherence.

I can't show users which personalData.isUserPCD is false in the beggining of the array, they need to be sorted with the default users.

Example:

compatibleProfessionals: [
  {
    _id: 1,
    userAdherence: 50,
    personalData: { isUserPCD: true },
    createdAt: '2020-12-17T16:49:12.819+00:00'
  },
  {
    _id: 2,
    userAdherence: 42,
    personalData: { isUserPCD: true },
    createdAt: '2019-12-15T16:49:12.819+00:00'
  },
  {
    _id: 3,
    userAdherence: 90,
    createdAt: '2017-02-15T16:49:12.819+00:00'
  },
  {
    _id: 4,
    userAdherence: 75,
    personalData: { isUserPCD: false },
    createdAt: '2020-12-17T16:49:12.819+00:00'
  },
  {
    _id: 5,
    userAdherence: 60,
    createdAt: '2020-12-17T16:49:12.819+00:00'
  },
]

So far, this is the code: (method receives the opportunity Id and an Integer for sorting)

exports.sortProfessionals = function (req, res) {
  if (parseInt(req.sort) === 99) {
    exports.processSortedProfessionals(req, res);
  } else {
    if (parseInt(req.sort) === 0) var sortParam = { userAdherence: -1 };
    else if (parseInt(req.sort) === 2) var sortParam = { createdAt: -1 };
    else if (parseInt(req.sort) === 1) var sortParam = { 'personalData.isUserPCD': -1, userAdherence: -1} //problem is here
    Opportunity.update(
      {
        _id: req.opportunity._id,
      },
      {
        $push: {
          compatibleProfessionals: {
            $each: [],
            $sort: sortParam
          },
        },
      }
    ).exec(function (err) {
      if (err) {
        console.log('Error sort compatibleProfessionals: ' + err);
      }
      exports.processSortedProfessionals(req, res);
    });
  }
};
0 Answers
Related