Skip to content

Instantly share code, notes, and snippets.

@willdages
Forked from adelevie/randomParse.rb
Created November 24, 2012 14:19
Show Gist options
  • Save willdages/4139857 to your computer and use it in GitHub Desktop.
Save willdages/4139857 to your computer and use it in GitHub Desktop.
randomParse.rb in javascript
var query = new Parse.Query("Classname");
query.count({
error: function(error) {
// Error counting objects
},
success: function(count) {
query.skip(Math.floor(Math.random() * (count - 1)));
query.first({
error: function(error){
// Error getting object
},
success: function(object) {
// Your random object
}
});
}
});
@willdages
Copy link
Author

This has to use 2 API calls, but is a great technique (credit to @adelevie) for getting a random object from a class with Parse.

@adelevie
Copy link

Here it in in Coffeescript (untested):

query = new Parse.Query("Classname")
query.count
  error: (error) -> 
    # Error counting objects
  success: (count) ->
    query.skip Math.floor(Math.random() * (count - 1))
    query.first
      error: (error) ->
      # Error getting object
      success: (object) ->
        # Your random object

@bklimt
Copy link

bklimt commented Nov 25, 2012

count and skip can be inefficient. Have you considered doing it this way instead?

https://parse.com/questions/is-it-possible-to-query-for-a-random-object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment