Home > Enterprise >  Conditional Mongo Filter
Conditional Mongo Filter

Time:09-29

Im looking into filtering only if the user wishes to filter based on a criteria.

I can filter just fine using $in but when the criteria used in the $in filter isn't provided, it complains that it needs an array. Replacing it with [] causes it to come back empty and I dont have a list of all possible values to insert (and not sure I would want to)

Any ideas? Colors below is the optional criteria. *Would be nice if there were a skip flag I could use.

 const profiles = await Profile.aggregate([
      {
        $geoNear: {
          ...geoFilter,
        },
      },
      {
        $match: {
          $and: [
            {
              _id: {
                $ne: Profile.castID(req.user.profileID),
              },
              colors: { $in: colors },
            },
          ],
        },
      },
      { $skip: skip },
      { $limit: limit },
    ]);

CodePudding user response:

Use this one:

var match = { _id: {$ne: Profile.castID(req.user.profileID)} };
if (typeof colors != "undefined") {
   match.colors = { $in: colors };
}

Profile.aggregate([
  {
    $geoNear: {
      ...geoFilter,
    },
  },
  { $match: match },
  { $skip: skip },
  { $limit: limit },
]);          

You don't need the $and, however in case you have situation where it is needed use

var match = [{ _id: {$ne: Profile.castID(req.user.profileID)} }];
if (typeof colors != "undefined") {
   match.push({colors: { $in: colors }});
}

Profile.aggregate([
  {
    $geoNear: {
      ...geoFilter,
    },
  },
  { $match: {$and: match}},
  { $skip: skip },
  { $limit: limit },
]);          
  • Related