Skip to content

Instantly share code, notes, and snippets.

@symn
Last active March 19, 2017 00:04
Show Gist options
  • Save symn/643c3a1107fb89739e8a to your computer and use it in GitHub Desktop.
Save symn/643c3a1107fb89739e8a to your computer and use it in GitHub Desktop.
Retrieve a single random record of a Sails.js model
/**
* Image.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
'image_path': 'STRING',
},
// retrieves a random record from the database
random: function(cb) {
var self = this;
this.count(function(err, num) {
if(err)
return cb(err, false);
var randm = Math.floor((Math.random() * num));
if(randm < 0) randm = 0;
self.find({skip: randm, limit: 1}).exec(function(err, image) {
return cb(err, image);
});
});
}
};
@slavafomin
Copy link

That's cool, thanks )

@gagan-bansal
Copy link

Great!

@thibaultboursier
Copy link

Thanks !

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