i'm trying to apply different filters along with nearby filter but user can also skip all other filter and just apply nearby filter. i'm getting the exact result if user selet tags or cuisines filter also. but when user skip both then it throws an exception. here is my code below
const query = [];
if (cuisines) {
const culinaryOptions = {
culinaryOptions: { $in: cuisines },
};
query.push(culinaryOptions);
}
if (tags) {
const tag = {
tags: { $in: tags },
};
query.push(tag);
}
if (nearest) {
maxDistance = 10;
sort = -1;
}
console.log(query);
return this.restaurantModel.aggregate([
{
$geoNear: {
near: {
type: 'Point',
coordinates: [parseFloat(longitude), parseFloat(latitude)],
},
distanceField: 'distanceFromMe',
maxDistance: maxDistance ?? 100 * METERS_PER_MILE, //!*** distance in meters ***!//
distanceMultiplier: 1 / 1609.34,
spherical: true,
},
},
{
$match: {
$or: query,
},
},
{ $unset: ['verificationCode', 'uniqueCode'] },
{ $sort: { location: sort ?? 1 } },
]);
} how to get only nearby restaurants if user skips all other filter
You should generate your query, on the basis of whether something is present in the query
or not. If nothing is there in the query
array don't add the stage $match
.
const query = [];
if (cuisines) {
const culinaryOptions = {
culinaryOptions: { $in: cuisines },
};
query.push(culinaryOptions);
}
if (tags) {
const tag = {
tags: { $in: tags },
};
query.push(tag);
}
if (nearest) {
maxDistance = 10;
sort = -1;
}
console.log(query);
let pipeline = [
{
$geoNear: {
near: {
type: 'Point',
coordinates: [parseFloat(longitude), parseFloat(latitude)],
},
distanceField: 'distanceFromMe',
maxDistance: maxDistance ?? 100 * METERS_PER_MILE, //!*** distance in meters ***!//
distanceMultiplier: 1 / 1609.34,
spherical: true,
}
}];
if (query.length > 0) {
pipeline = [...pipeline, {
$match: {
$or: query,
},
}];
}
pipeline = [...pipeline, { $unset: ['verificationCode', 'uniqueCode'] },
{ $sort: { location: sort ?? 1 } } ];
return this.restaurantModel.aggregate(pipeline);