Last active
December 20, 2015 11:29
-
-
Save jamlfy/6123943 to your computer and use it in GitHub Desktop.
Random con Query en mongoose Nodejs
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 = 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