find() method in mongodb returns undefined

和自甴很熟 提交于 2021-01-29 08:44:04

问题


I am trying to create a route to retrieve the records with nearby location coordinates. I checked the logs and found the "docs" value as undefined. What am I going wrong with?

router.get('/userlist/:lat/:lng', function (req, res) {
    var db = req.db;
    var lat = req.params.lat, lng = req.params.lng;
    console.log("lat "+lat);
    console.log("lng "+lng);
    var collection = db.get('userlist');
    collection.find({
        "location": {
         $nearSphere: {
           $geometry: {
              type: "Point" ,
              coordinates: [ lat , lng ]
           }
         }
       }
    }, {}, function (e, docs) {      
        docs = JSON.stringify(docs);
        console.log("docs "+docs);
        res.send(docs);        
    });
});

I am storing the JSON data as shown in the screenshot below.


回答1:


The location should be stored in the format:-

"location" : {
        "type" : "Point",
        "coordinates" : [ 
            -70.845654, 
            42.146249
        ]
    }

The geojson point should be an object and not an array.




回答2:


As @Webdev said, the coordinates are stored as strings and shall not be. But I was unable to store them in numeric form using mongoose. So I am parsing the latitude and the longitude into float in the find query itself and it works.



来源:https://stackoverflow.com/questions/59840828/find-method-in-mongodb-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!