如何在地理空间搜索中使用MongoDB和Mongoose返回距离?

如何在地理空间搜索中使用MongoDB和Mongoose返回距离?,mongodb,mongoose,Mongodb,Mongoose,我将Mongoose 3.5.3与Node.js 0.8.8一起使用,结果中没有返回与给定点的距离,这让我感到惊讶。是否可以允许返回距离?它一定有它,因为我的结果似乎是按距离排序的,正如人们所期望的那样 exports.nearBuilding = function (req, res, next) { var area = { center: [parseFloat(req.params.longitude), parseFloat(req.params.latitud

我将Mongoose 3.5.3与Node.js 0.8.8一起使用,结果中没有返回与给定点的距离,这让我感到惊讶。是否可以允许返回距离?它一定有它,因为我的结果似乎是按距离排序的,正如人们所期望的那样

exports.nearBuilding = function (req, res, next) {
    var area = {
        center: [parseFloat(req.params.longitude), parseFloat(req.params.latitude)],
        radius: parseFloat(req.params.distance) / 3963.192 };

    var query = Building.find().where('coords').within.centerSphere(area);

    query.exec(function (error, docs) {
        var records = {'records': docs};
        if (error) {
            process.stderr.write(error);
            res.send(error, 500);
        }
        if (req.params.callback !== null) {
            res.contentType = 'application/javascript';
        }
        res.send(records);
        return next();
    });
};

您可以使用geoNear函数返回距离:

Building.collection.geoNear(longitude, latitude, {maxDistance: radius }, cb);
以下是API选项:

/**
 * Execute the geoNear command to search for items in the collection
 *
 * Options
 *  - **num** {Number}, max number of results to return.
 *  - **maxDistance** {Number}, include results up to maxDistance from the point.
 *  - **distanceMultiplier** {Number}, include a value to multiply the distances with allowing for range conversions.
 *  - **query** {Object}, filter the results by a query.
 *  - **spherical** {Boolean, default:false}, perform query using a spherical model.
 *  - **uniqueDocs** {Boolean, default:false}, the closest location in a document to the center of the search region will always be returned MongoDB > 2.X.
 *  - **includeLocs** {Boolean, default:false}, include the location data fields in the top level of the results MongoDB > 2.X.
 *  - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).
 *
 * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order.
 * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order.
 * @param {Objects} [options] options for the map reduce job.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured.
 * @return {null}
 * @api public
在您的情况下,您可以这样做:

       exports.nearBuilding = function (req, res, next) {

        var query = Building.collection.geoNear(parseFloat(req.params.longitude), parseFloat(req.params.latitude), { distance: parseFloat(req.params.distance) / 3963.192}, function (error, docs) {

            if (error) {
                process.stderr.write(error);
                res.send(error, 500);
            }
            if (req.params.callback !== null) {
                res.contentType = 'application/javascript';
            }
            // Docs are turned as an array of objects that contain distance (dis) and the object (obj). 
            // Let's concatenate that into something cleaner - i.e. the distance as part of object

            var results = []
            docs.forEach(function(doc) {
                doc.obj.distance = doc.dis;
                results.push(doc.obj);
            });
            var records = {'records': results};      

            res.send(records);
            return next();
        });
    };
当前(3.8版)Mongoose构建为此提供了一种基于
模型的方法:

Building.geoNear(
[long,lat],
{maxDistance:300,球形:true},
函数(错误、结果、统计){
//结果是一个结果对象数组,如:
//{dis:distance,obj:doc}
}
);

如果您使用2dsphere坐标(您应该这样做),代码应该如下所示。距离d以米为单位

var point={坐标:[lng,lat],类型:'point'};
geoNear(点,{maxDistance:d,sphereal:true},函数(err,docs){
if(err){返回下一个(err);}
var实体=[];
docs.forEach(函数(doc){
doc.obj.distance=doc.dis;
实体推送(doc.obj);
});
res.json(实体);

});杰出!我稍微更新了一下,这样forEach就不会出错,但这正是我想要的…谢谢!geoNear似乎已从mongoose 5.4.16中删除…
Query.prototype.near()
不会在promise解析的数组中的对象中返回
dis
。是的,我也注意到了这一点,你知道如何从较新的mongoose版本中获得它吗?