Last active
March 19, 2017 00:04
-
-
Save symn/643c3a1107fb89739e8a to your computer and use it in GitHub Desktop.
Retrieve a single random record of a Sails.js model
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
/** | |
* 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); | |
}); | |
}); | |
} | |
}; |
Great!
Thanks !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's cool, thanks )