3

I'm newbie of Sails JS framwork and I'm trying to write a small quiz app. Each quiz, my app will select 6 random questions from question collection.

Is it possible in SailsJS 0.11, MongoDB 3.6.8? How can I do that?

Many thanks

Savior Nguyen
  • 87
  • 1
  • 10

1 Answers1

7

You can call find method with skip and limit criteria.

Question
  .count()
  .then(count => Question.find().limit(6).skip(parseInt(Math.random() * count)))
  .then(questions => questions.sort(() => 0.5 - Math.random()))
  .then(questions => doSomethingWith(questions))
  .catch(sails.log.error);
Taha Boulehmi
  • 227
  • 1
  • 11
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34
  • Thank you for answer my question. Is your solution return 6 questions next to each other? Like: 1 2 3 4 5 6 7 8 9 10 and return 3 4 5 6 7 8. I need something like: 1 3 5 6 7 9 – Savior Nguyen Oct 18 '15 at 11:39
  • You can apply `sort` method on array though and randomize it. I will update answer in few mins. – Eugene Obrezkov Oct 18 '15 at 14:48