Skip to content

Instantly share code, notes, and snippets.

@joeylin
Last active August 29, 2015 14:04

Revisions

  1. joeylin renamed this gist Aug 6, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. joeylin created this gist Jul 28, 2014.
    60 changes: 60 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    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;
    }