Skip to content

Instantly share code, notes, and snippets.

@switz
Last active December 22, 2015 06:38
Show Gist options
  • Save switz/6432049 to your computer and use it in GitHub Desktop.
Save switz/6432049 to your computer and use it in GitHub Desktop.
module.exports = function (options) {
var randFn = (options && options.fn) || Math.random;
var randCoords = function () { return [randFn(), randFn()] } ;
function random(schema, options) {
var path = (options && options.path) || 'random';
var field = {};
field[path] = {
type: { type: String, default: 'Point' },
coordinates: { type: [Number], default: randCoords }
};
var index = {};
index[path] = '2dsphere';
schema.add(field);
schema.index(index);
schema.statics.findRandom = function (query, callback) {
var self = this;
if (typeof query === 'function') {
callback = query;
query = {};
}
query[path] = query[path] || {
$near: {
$geometry: { type: 'Point', coordinates: randCoords() }
}
};
self.findOne(query, function (err, doc) {
if (err) return callback(err);
callback(null, doc);
});
};
schema.statics.syncRandom = function (callback) {
this.update({}, { random: { coordinates: randCoords(), type: 'Point' } }, { multi: true }, callback);
}
}
return random;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment