简体   繁体   中英

Mongoose query on GeoJSON objects

I am trying to query some restaurants ordered by their distance to a certain location (user's location). I have a "restaurants" collection with documents like this:

{
   ...
   "location": {
      "type": "Point",
      "coordinates": [7.756894, 45.093654]
   },
   ...
}

My Mongoose schema looks like this:

const restaurantSchema = new mongoose.Schema({
   ...
   location: {
        type: {
            type: String,
            enum: ['Point'],
            required: true
        },
        coordinates: {
            type: [Number],
            required: true
        }
    },
   ...
});

restaurantSchema.index({location: '2dsphere'});

module.exports = mongoose.model('Restaurant', restaurantSchema)

on this collection I have defined the following index:

在此处输入图像描述

In my nodejs server I have the following function that tries to retrieve the restaurants (ordered by distance) near the user's current location (received in the request headers):

getRestaurantsNearYou: function(req, res){
      if(req.headers.lng && req.headers.lat){
        Restaurant.find({
            location: {
                $near: {
                    $geometry: {
                        type : "Point",
                        coordinates : [parseFloat(req.headers.lng), parseFloat(req.headers.lat)]
                    },
                    $maxDistance: 5000
                }
            }
        }).then(function(err, restaurants){
            console.log(restaurants);
            return res.json({success: true, restaurants: restaurants});
        }).catch(err=>{if(err) throw err;});
      }else{
          return res.json({success: false, msg: res.__('invalidArgumentsErrorMsg')})
      }
}

This code throws no errors, however the return of this function is just

{
   success: true
}

and the variable "restaurants" that I'm trying to return is undefined.

What am I doing wrong?

I was being stupid. Everything was working just fine, only the callback wasn't getting the right variables. Changing my function to this solved the problem:

if(req.headers.lng && req.headers.lat){
        var restaurants = await Restaurant.find({
            location: {
                $near: {
                    $geometry: {
                        type : "Point",
                        coordinates : [parseFloat(req.headers.lng), parseFloat(req.headers.lat)]
                    },
                    $maxDistance: 50000
                }
            }
        });
        console.log(restaurants);
      }else{
          return res.json({success: false, msg: res.__('invalidArgumentsErrorMsg')})
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM