Skip to content

Instantly share code, notes, and snippets.

@joeylin
Last active August 29, 2015 14:04
Show Gist options
  • Save joeylin/04787b040641fd313cd2 to your computer and use it in GitHub Desktop.
Save joeylin/04787b040641fd313cd2 to your computer and use it in GitHub Desktop.
mongoose random search code
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