Hello everyone!
I’m new to MongoDB and would like to ask for help/hint with the following use cases:
I have 3 collections: user, request,offer
I am storing the geoJSON point only in the user collection as an optional value (can be changed in the profile page) togeter with a default maxDistance = 5000 m for selecting the Range.
I would like to have queries/aggregations from my API that does the following:
- fetch all requests with status 0,1 whithin the maxDistance to the current user
- calculates a fild distance (virtual or calculated field) for the requests / offers to see which requests/offers are how far from the logged in users geocoordinstes.
i tried the following functions to manage the above goals. i could manage both to work with 2 separated routes, but i would like to combine them into one. I get an errmsg: “$geoNear, $near, and $nearSphere are not allowed in this context, as these operators require sorting geospatial data. If you do not need sort, consider using $geoWithin instead.”
the codes i was using:
const distanceQuery = await User.aggregate([
// Step 2: Lookup the user info (including their geoLocation)
{
$match: {
// Step 1: Calculate distances using $geoNear
"addressObj.geoLocation": {
$geoNear: {
near: {
type: "Point",
coordinates: [Lon, Lat],
},
distanceField: "distanceToUser", // The field that will contain the calculated distance
maxDistance: maxDist, // The maximum distance in meters
spherical: true, // Use spherical distance calculation (more accurate for large distances)
},
},
},
},
// Step 4: Project the fields you want to return
{
$project: {
_id: 1,
distanceToUser: 1, // Include the calculated distance
},
},
]);
// Find requests where rUserId geolocation is within the maxDistance
const requestsWithinDistance = await Request.aggregate([
{
$lookup: {
from: "users",
localField: "rUserId",
foreignField: "_id",
as: "User",
},
},
{
$match: {
"User.addressObj.geoLocation": {
$geoWithin: {
$centerSphere: [[Lon, Lat], maxDist / 6378100], // Convert maxDistance from meters to radians
},
},
rStatus: { $in: [0, 1] },
},
},
{
$project: {
// "User.addressObj.geoLocation": 1, // include only the geoLocation object
_id: 1,
rCategory: 1,
rText: 1,
rDate: 1,
},
},
]);
// Return the filtered requests with distance info
res.status(200).json(distanceQuery, requestsWithinDistance);
Thanks for any hints/tips in Advance!```