2

我试图根据保存的纬度和经度信息的值在我的 mongoDB 数据库中查找一些记录。我想在我的收藏中应用以下功能:

exports.findDistance = findDistance(latitude, longitude) {
    console.log('calculating with lat = ' + latitude + ' and longitude = ' + longitude);
    var radian = 0.0174532925;
    var x = Math.pow(Math.sin((latitude - this.latitude) * radian / 2), 2);
    var y = Math.cos(latitude - radian) * Math.cos(this.latitude - radian);
    var z = Math.pow(Math.sin((longitude - this.longitude) * radian/2), 2);
    var result = 2*3956*Math.asin(Math.sqrt(x + y * z));
    return result < 10;
}

当我的计算结果小于 10 时,此函数返回 true(我使用数据库中的纬度和经度信息,由 'this' 对象和两个参数引用)。如何从 mongoDB 获取适用于此功能的所有消息?

我尝试了以下方法:

exports.index = function(req, res) {
    var latitude = value1;
    var longitude = value2;
    Message.find(Message.findDistance, [], function(err, msgs) {
        // render the page
    });
}

但是,我的 findDistance 函数似乎没有被 mongoose find 函数调用(在我的开发人员控制台中没有看到任何输出,我只是从我的 mongoDB 集合中返回了所有结果)。另外,如何将纬度和经度参数传递给 findDistance 函数?

我的消息架构如下所示:

Message = new Schema({
    text: { type: String, required: true },
    parent: String,
    user: ObjectId,
    latitude: Number,
    longitude: Number,
    date: { type: Date, default: Date.now }
});

有人能帮我吗?:)

4

2 回答 2

1

您的 findDistance 函数需要在 MongoDB 中定义,而不是在 node.js 中,这样它才能在运行时访问数据库字段。幸运的是,MongoDB 将 JavaScript 用于其存储过程,因此该函数应该可以工作。

有关存储和使用 MongoDB 存储过程的说明,请参见此处

于 2011-05-03T05:44:06.707 回答
0

它等同于存储过程,但不一样。并且建议避免使用 MongoDB 存储函数。

更多信息:http ://docs.mongodb.org/manual/applications/server-side-javascript/

于 2013-01-10T07:29:20.977 回答