简体   繁体   中英

Find mongodb (in mongoose+node.JS) records based on a condition

I'm trying to find some records in my mongoDB database based on the values of saved latitude and longitude information. I want to apply following function with a find on my collection:

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;
}

This function returns true when my calculated result is smaller than 10 (I use latitude and longitude information from my database, referenced by the 'this' object, and the two parameters). How can I get all messages from mongoDB that apply to this function?

I have tried the following:

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

However, my findDistance function doesn't seem to be called by the mongoose find function (no output seen in my developer console and I just get all results returned from my mongoDB collection). Also, how can I pass the latitude and longitude parameters to the findDistance function?

My Message Schema looks as follows:

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

Can someone help me? :)

Your findDistance function needs to be defined in MongoDB, not in node.js, so that it has access to the database fields when it runs. Luckily, MongoDB uses JavaScript for its stored procedures, so the function should work.

Seehere for instructions on storing and using MongoDB stored procedures.

Its equavilant to stored procedure but not same. And it is recommended to avoid using MongoDB stored function.

For more Info: http://docs.mongodb.org/manual/applications/server-side-javascript/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM