Reputation: 11
I am filtering users based on some attributes in the user collection and based on coordinates present in the location collection as in the below code. I have to Filter the location radius after the match pipeline because it will reduce the number of documents to populate. But I am getting this error I'm not getting any points on how to cope with this. Error: $geoNear is only valid as the first stage in a pipeline.
One thing more, I have to lookup up locations first, to apply the geoNear query on this. Or if there is any better sequence to do let me know. And if I'm not wrong I am applying geoNear on users' collections, which should be on locations collections.
Code:
if (locationRange) {
const coordinates = user.location.coordinates.coordinates;
locationFilter = {
near: {
type: 'Point',
coordinates: [coordinates[0], coordinates[1]],
},
distanceField: "distance",
maxDistance: locationRange.max,
minDistance: locationRange.min,
spherical: true
};
}
const res = await User.aggregate([
{
$match: match,
},
{
$lookup: {
from: 'locations',
localField: 'location',
foreignField: '_id',
as: 'location',
},
},
{
$unwind: {
path: '$location',
preserveNullAndEmptyArrays: true,
},
},
{ ...(Object.keys(locationFilter).length && { $geoNear: locationFilter }) },
{ $skip: (page - 1) * limit },
{ $sort: sortingOptions },
{ $limit: limit },
]);
I am trying to filter users based on their role and some other attributes. Also want to filter based on their location.
Upvotes: 1
Views: 46