2015-10-14 54 views
2

我是Sails JS framwork的新手,我正在尝试写一个小测验应用程序。每个测验,我的应用程序将从问题收集中选择6个随机问题。Sails JS:从MongoDB中选择随机记录?

SailsJS 0.11,MongoDB 3.6.8有可能吗? 我该怎么做?

非常感谢

+0

http://stackoverflow.com/questions/2824157/random-record-from-mongodb – JohnnyHK

回答

4

你可以调用findskiplimit标准。

Question 
    .count() 
    .then(count => Question.find().limit(6).skip(Math.random() * count)) 
    .then(questions => questions.sort(() => 0.5 - Math.random())) 
    .then(questions => doSomethingWith(questions)) 
    .catch(sails.log.error); 
+0

的可能的复制谢谢你回答我的问题。您的解决方案是否相互返回6个问题?喜欢:1 2 3 4 5 6 7 8 9 10并返回3 4 5 6 7 8.我需要如下所示:1 3 5 6 7 9 –

+0

您可以在数组上应用'sort'方法并随机化它。我会在几分钟内更新答案。 – ghaiklor

+0

它正在工作!非常感谢 –