2

I've been digging Bookshelf documentation but I can't find enough information to get 5 random users from the database. Right now, the following code retrieves all users.

User.fetchAll().then((users) => {

});

However, is it possible to do something like this?

User.take(5).random().get().then((users) => {
    // random 5 users in users collection
});

I really don't want to write raw SQL but I'm fine doing it inside ORM using .query callbacks if necessary.

Aris
  • 2,978
  • 5
  • 22
  • 31

1 Answers1

3

There's a shuffle method in the included methods brought in from lodash.

User.shuffle().take(5).get().then((users) => {
    // random 5 users in users collection
});
Gangstead
  • 4,152
  • 22
  • 35
  • I have around 100k entries on my database so I cannot rely on collection methods. It has to be done directly in the SQL. – Aris Aug 13 '16 at 08:01
  • That changes the question. You will have to drop into a raw query and use something from http://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql – Gangstead Aug 14 '16 at 04:10