MongoDB聚合,geNear并迭代callback

我有一个问题,我找不到解决scheme。 我有一些MongoSchemas用于存储来自用户的地理定位。 手机每隔5分钟发送一次经纬度。 这个API是完美的。

Mongo-Schema看起来像:

// Importing Node packages required for schema const mongoose = require('mongoose'); const Schema = mongoose.Schema; //= =============================== // User Schema //= =============================== const GeolocationSchema = new Schema({ loc: { type: { type: String }, coordinates: { type: [Number], index: '2dsphere' } }, user: { type: Schema.Types.ObjectId, ref: 'User' } }, { timestamps: true }); module.exports = mongoose.model('Geolocation', GeolocationSchema); 

现在,我想计算过去有5分钟甚至更短的“updateAt”时间戳的用户。 这意味着一个或多个用户在过去的5分钟内可以处于例如500m的距离。 这应该是一个匹配。 为此,我使用Mongo聚合,我想迭代callback结果并从结果中提取user._id以构build匹配。

这是我试过的:

 const Geolocation = require('../models/geolocation') User = require('../models/user'), config = require('../config/main'); exports.setGeolocation = function (req, res, next) { // Only return one message from each conversation to display as snippet console.log(req.user._id); var geoUpdate = Geolocation.findOneAndUpdate( { user: req.user._id }, { loc: { type: 'Point', coordinates: req.body.coordinates.split(',').map(Number) }, user: req.user._id }, {upsert: true, new: true, runValidators: true}, // options function (err, doc) { // callback if (err) { console.log(err); } }); // create dates for aggregate query var toDate = new Date( (new Date()).getTime()); var fromDate = new Date( (new Date()).getTime() - 5000 * 60 ); var match = Geolocation.aggregate([ { $geoNear: { near: { type: "Point", coordinates: req.body.coordinates.split(',').map(Number) }, distanceField: "dist.calculated", maxDistance: 500, includeLocs: "dist.location", uniqueDocs: true, query: { user: {$ne: req.user._id } , updatedAt: { $gte: fromDate,$lte: toDate }}, num: 5, spherical: true } }], function (err, doc){ //here I´m going in trouble correctly parsing doc var str = JSON.stringify(doc); var newString = str.substring(1, str.length-1); var response = JSON.parse(newString); console.log(response.user); }); res.sendStatus(200); }; 

正如你所看到的,我在parsing“doc”-callback来迭代文档时遇到了麻烦。 如果我想将它parsing为jSON,我会在位置1上得到一个令牌错误。如果我有两个以上的结果,我会在位置288上得到一个错误。

这就是为什么我试图parsing和“文档”串联。 但是这不能正常工作。

也许,有人可以帮我解决。 我不熟悉mongo函数,因为我从头开始,也许有一个更好的解决scheme,但我不能find其他的东西来计算geoNear,然后迭代结果。

Thx在所有谁可以帮助…