【问题标题】:Find mongodb (in mongoose+node.JS) records based on a condition根据条件查找mongodb(在mongoose+node.JS中)记录
【发布时间】:2011-08-17 06:01:44
【问题描述】:

我正在尝试根据保存的纬度和经度信息的值在我的 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 }
});

有人可以帮助我吗? :)

【问题讨论】:

    标签: javascript mongodb node.js geolocation mongoose


    【解决方案1】:

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

    有关存储和使用 MongoDB 存储过程的说明,请参阅 here

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多