Home > Net >  mongodb - how to pass a variable field in geoNear?
mongodb - how to pass a variable field in geoNear?

Time:10-02

coordinates are stored in array

const userLocArray = userLoc.split(',');

How to use this array in geoNear coordinates?

userLocArray[0], userLocArray[1] does not work

$geoNear: {
   near: { type: "Point", coordinates: [userLocArray[0], userLocArray[1]] },
   distanceField: "calculatedDist",
   spherical: true
}

On the client side:

       const userLoc = currentUser.location.coordinates;
        console.log(userLoc)//this is [31.4998, -61.4065]
let { data: matches } = useSWR(`/api/myapi?userIdToMatch=${_id}&userLoc=${userLoc}&page=${matchIndex}`, fetcher,); 
   

In the api

handler.get(async (req, res) => {
  const {userIdToMatch, userLoc} = req.query;
  const userLocArray = userLoc.split(',');

CodePudding user response:

coordinates is an array of numbers, you are passing strings. Try this:

$geoNear: {
   near: { type: "Point", coordinates: [parseFloat(userLocArray[0]), parseFloat(userLocArray[1])] },
   distanceField: "calculatedDist",
   spherical: true
}

You can also use Number instead of parseFloat.

  • Related