Last active
August 29, 2015 14:04
-
-
Save joeylin/04787b040641fd313cd2 to your computer and use it in GitHub Desktop.
mongoose random search code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function (options) { | |
var randFn = (options && options.fn) || Math.random; | |
function random(schema, options) { | |
var path = (options && options.path) || 'random'; | |
var field = {}; | |
field[path] = { | |
type: { type: String, default: 'Point' }, | |
coordinates: { type: [Number], default: function () { return [randFn(), randFn()] } } | |
}; | |
var index = {}; | |
index[path] = '2dsphere'; | |
schema.add(field); | |
schema.index(index); | |
schema.statics.findRandom = function (query, callback) { | |
var self = this; | |
var coords = [randFn(), randFn()]; | |
if (typeof query === 'function') { | |
callback = query; | |
query = {}; | |
} | |
query[path] = query[path] || { | |
$near: { | |
$geometry: { type: 'Point', coordinates: coords } | |
} | |
}; | |
self.findOne(query, function (err, doc) { | |
if (err) return callback(err); | |
callback(null, doc); | |
}); | |
}; | |
schema.statics.findMultiRandom = function (query, count, callback) { | |
var self = this; | |
var coords = [randFn(), randFn()]; | |
if (typeof query === 'function') { | |
callback = query; | |
query = {}; | |
} | |
query[path] = query[path] || { | |
$near: { | |
$geometry: { type: 'Point', coordinates: coords } | |
} | |
}; | |
self.find(query).limit(count).exec(function(err, docs) { | |
if (err) return callback(err); | |
callback(null, docs); | |
}); | |
}; | |
} | |
return random; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment