Skip to content

Instantly share code, notes, and snippets.

@jamlfy
Last active December 20, 2015 11:29
Show Gist options
  • Save jamlfy/6123943 to your computer and use it in GitHub Desktop.
Save jamlfy/6123943 to your computer and use it in GitHub Desktop.
Random con Query en mongoose Nodejs
module.exports = exports = function (mongo){
var mng = mongo || require('mongoose');
var Query = mng.Query;
Query.prototype.random = function ( query, func ){
var q = typeof query === 'object' ? query : this.query;
var f = typeof query === 'function' ? query : func;
if(!( typeof f === 'function' )) retrun new Error("Is not a function");
this.count(q, function (err, count) {
if( err || count =< 0 ) return f( err || new Error("Query is 0"), null);
this.findOne(q).skip( Math.floor(Math.random() * count) ).exec(f);
});
};
mng.Query = Query;
if( !mongo ) return mng;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment