javascript - 根据条件查找mongodb(在mongoose+node.JS中)记录

标签 javascript mongodb node.js geolocation mongoose

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

有人可以帮助我吗? :)

最佳答案

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

参见 here有关存储和使用 MongoDB 存储过程的说明。

关于javascript - 根据条件查找mongodb(在mongoose+node.JS中)记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5862058/

相关文章:

javascript - NodeJS - 日志记录 - 日志记录中的请求或堆栈号

javascript - 类型错误 : Cannot read property 'email' of undefined in nodejs

javascript - 修复 Javascript 中的常见 URL 错误

javascript - 将 Javascript 字典转换为 Python 字典

javascript - 使用 Ryan Fait "Check All"自定义表单元素时的 's "函数”

javascript - jQuery 从事件中读取数据

javascript - Mongoose:如何更新/保存文档?

node.js - 这个错误: Falsy value for recipient key 'registrationTokens' 是什么意思

javascript - mongodb基于数组的唯一索引

node.js - Node.js 中的 process.hrtime() 和 process.hrtime.bigint() 函数是指什么时间?