Created
April 21, 2014 01:13
-
-
Save ccorcos/11129592 to your computer and use it in GitHub Desktop.
get a random document from a collection (meteor, mongodb)
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
randomInRange = function(min, max) { | |
var random = Math.floor(Math.random() * (max - min + 1)) + min; | |
return random; | |
} | |
randomFromCollection = function(C) { | |
return function() { | |
c = C.find().fetch(); | |
i = randomInRange(0, c.count()) | |
return c[i] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using findone appears a lot more efficient, you could just feed the random number (which you calculate with randomInRange(0,collection.count()) into the skip argument
http://docs.meteor.com/#/full/findone