我在测试API时收到控制台的错误消息。我正在尝试将从geoNear方法返回的结果推送到数组中,但不是返回包含near-by位置文档的数组,而是返回 undefined 。即使我的URL中没有包含坐标的查询字符串,我的API至少应该响应一个空数组。在路上肯定出了什么问题,我真的坚持这个。错误消息如下:
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property 'forEach' of undefined
at C:\Users\Forrest\Desktop\loc8r\app_api\controllers\locations.js:39:10
“Loc”是我的模型的名称,我的控制器看起来像这样
module.exports.locationsListByDistance = function(req, res) {
var lng = parseFloat(req.query.lng);
var lat = parseFloat(req.query.lat);
var point = {
type: "Point",
coordinates: [lng, lat]
};
var geoOptions = {
spherical: true,
maxDistance: theEarth.getRadsFromDistance(20),
num: 10
};
Loc.geoNear(point, geoOptions, function(err, results, stats) {
var locations = [];
results.forEach(function(doc) { // Can't read property 'forEach' of undefined
locations.push({
disance: theEarth.getDistanceFromRads(doc.dis),
name: doc.obj.name,
address: doc.obj.address,
rating: doc.obj.rating,
facilities: doc.obj.facilities,
_id: doc.obj._id
});
});
sendJsonResponse(res, 200, locations);
});
};