Node.js 猫鼬:我如何获得5个不同条件的随机记录?
我的模型:问题(仅给出与问题相关的数据,所有其他内容都被删除) 我的数据库里有大约250多个问题 我的要求:我需要5个随机问题,第一个和第二个问题应该是“类型1”,第三个问题应该是“类型2”,第四个应该是“类型3”,第五个应该是“类型1” 我的想法是:Node.js 猫鼬:我如何获得5个不同条件的随机记录?,node.js,mongodb,express,mongoose,database,Node.js,Mongodb,Express,Mongoose,Database,我的模型:问题(仅给出与问题相关的数据,所有其他内容都被删除) 我的数据库里有大约250多个问题 我的要求:我需要5个随机问题,第一个和第二个问题应该是“类型1”,第三个问题应该是“类型2”,第四个应该是“类型3”,第五个应该是“类型1” 我的想法是: async.parallel({ Type1: function(callback) { Question.find({}, { questionType: "Type1" }).l
async.parallel({
Type1: function(callback) {
Question.find({}, {
questionType: "Type1"
}).limit(3).exec(function (err, questions) {
callback(null, questions)
})
},
Type2: function(callback) {
Question.find({}, {
questionType: "Type2"
}).limit(1).exec(function (err, questions) {
callback(null, questions)
})
},
Type3: function(callback) {
Question.find({}, {
questionType: "Type3"
}).limit(1).exec(function (err, questions) {
callback(null, questions)
})
},
},
function(err, results) {
// Take all results here order it as per requirement and return
//results.Type1, results.Type2, results.Type3
// return the result in required order.
})
但我知道这不是有效的方法。当它执行3个查询时,之后还必须更改顺序
问题:最好/更好的方法是什么
提前感谢:)有多种方法可以做到这一点。最简单的方法是对文档进行随机编号,然后使用从集合中获取文档 如果要跳过大量文档,这可能会很昂贵 另一个解决方案是为每个问题类型和该字段上的查询生成一个唯一的整数字段(类似于MySQL中的自动增量)
async.parallel({
Type1: function(callback) {
Question.find({}, {
questionType: "Type1"
}).limit(3).exec(function (err, questions) {
callback(null, questions)
})
},
Type2: function(callback) {
Question.find({}, {
questionType: "Type2"
}).limit(1).exec(function (err, questions) {
callback(null, questions)
})
},
Type3: function(callback) {
Question.find({}, {
questionType: "Type3"
}).limit(1).exec(function (err, questions) {
callback(null, questions)
})
},
},
function(err, results) {
// Take all results here order it as per requirement and return
//results.Type1, results.Type2, results.Type3
// return the result in required order.
})