【发布时间】:2016-06-15 21:53:32
【问题描述】:
我有以下代码。使用 $geoNear,我找到了离给定 gps 坐标最近的中转站。有些人可能知道,$geoNear 只返回最近点的位置(loc)。为了获取最近站点的详细信息,我使用位置查询 STOPS 集合。
问题是,它随机返回 undefined。当我从 mongo shell 查询 stops 集合时,使用 Agency_key 和 loc 参数我确认数据在那里。我怀疑这个问题可能是由异步引起的,但我不知道为什么。 我试图将我的问题简化为 '在 forEach 循环中调用异步函数',但到目前为止我什么都没有。
为什么返回未定义?
...
TmStop.aggregate([{
$geoNear: {
near: [lon, lat],
maxDistance: radiusInDegrees,
includeLocs: "distance.location",
distanceField: "distance.calculated",
query: {
agency_key: {
$in: agencyKeys
}
}
}
}, {
$project: {
route_id: 1,
route_type: 1,
direction_id: 1,
"distance.calculated": 1,
"distance.location": 1
}
}])
.exec(function(e, results) {
if (e) {
console.log('e->', e.errmsg);
var res = "Something went wrong with the database: " + e;
cb(e, res);
} else if (!e) {
if (results.length) {
console.log('results->', results.length);
var i = 0;
results.forEach(function(result, index) {
console.log(index, result);
Stop.find({
agency_key: {
$in: agencyKeys
},
loc: result.distance.location
})
.exec(function(e, stop) {
if (e) {
throw new Error('Error getting stop due to:' + e);
}
var obj = {};
obj.route_id = result.route_id;
obj.route_type = result.route_type;
obj.direction_id = result.direction_id;
obj.distance = result.distance.calculated;
obj.locationUsed = result.distance.location;
// console.log('### ', index, ' ####');
// console.log('@Stop.find agencyKeys-> ', agencyKeys);
// console.log('@Stop.find loc->', result.distance.location);
// console.log(stop[0]);
obj.stop = stop[0];
objArr.push(obj);
i++;
if (i === results.length) {
cb(e, objArr);
}
});
}); //end of forEach
} else {
cb(e, []);
}
}
});
【问题讨论】:
标签: javascript node.js mongodb mongoose