mongodb - 如何在地理空间搜索中使用 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.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();
        });
    };

关于mongodb - 如何在地理空间搜索中使用 MongoDB 和 Mongoose 返回距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16156157/

相关文章:

mongodb - 拉推原子操作?

node.js - 如何从结果中删除 mongo 特定字段(NodeJS、Mongoose)

node.js - 使用 Node js(express) 在 mongodb atlas 中发布时出现 UnknownReplWriteConcern 错误

mongodb - Mongoose 中间件如何工作以及什么是 next()?

node.js - 使用 Mongoose 查找byid 并更新同级

javascript - 我如何将 dd-mm-yyyy 之类的日期转换为 ISO 日期格式,以存储在 mongoDB 中

Java查询mongodb查找列表大小小于n的文档

mongodb - mongodb 中两个字段的总出现次数

node.js - MongoDB在docker-compose环境中通过mongoose与nodeJs连接

node.js - npm install mongoose : shasums. txt 丢失