Imagine having the following entries in your "Request" collection:
{
pickup: {
coords: null
},
meetup: {
coords: [ someLng, someLat ]
}
},
{
pickup: {
coords: null
},
meetup: {
coords: [ someLng, someLat ]
}
},
{
pickup: {
coords: [ someLng, someLat ]
},
meetup: {
coords: [ someLng, someLat ]
}
}
The objective is to present the user with a sorted request list based on distance from their location, starting from the nearest request.
If pickup.coords
exists, it should be used as the positional reference for subsequent calculations; otherwise, meetup.coords
should be used.
I attempted to implement this using $cond
, but encountered an error and am unsure about its correct usage.
This is what I thought could work:
const query = {
$cond: {
if: {
'pickup.coords': { $exists: true }
},
then: {
// use pickup.coords as reference for distance calculation
},
else: {
// use meetup.coords as reference for distance calculation
}
}
}
const requests = await Request.find( query )
Error:
unknown top-level operator: $cond
The final implementation will likely involve more complexity, including pagination using limit
and utilizing the $near
operator along with indexing. But getting through this initial step would be a good start :-)
Any assistance you can offer would be greatly appreciated!