我想根据数组中的某些条件查找文档 例如:
subscriptions=[
{teacher: 'john', student:'david' ,course:'math'},
{teacher: 'john', student:'david' ,course:'english'},
{teacher: 'matt', student:'max' ,course:'math'}]
我想在Exam
集合中找到以下位置:老师,学生和课程均基于此数组:
subscriptions.forEach(sub=>{
Exam.find({teacher:sub.teacer, student:sub.student, course:sub.course},(err,res)=>{})})
无论如何,我不能在for循环中调用find,我应该使用async
库吗?我认为此查询有更好的方法,不需要循环
答案 0 :(得分:0)
您应该选择使用或运算符而不是循环选择:
<Color x:FactoryMethod="FromRgba" x:Key="TransparentBlack">
<x:Arguments>
<x:Double>0.0</x:Double>
<x:Double>0.0</x:Double>
<x:Double>0.0</x:Double>
<x:Double>0.5</x:Double>
</x:Arguments>
</Color>
答案 1 :(得分:0)
如果要获取与数组条目之一匹配的所有文档:
const subscriptions = [{
teacher: 'john',
student: 'david',
course: 'math',
},
{
teacher: 'john',
student: 'david',
course: 'english',
},
{
teacher: 'matt',
student: 'max',
course: 'math',
},
];
Exam.find({
$or: subscriptions,
})
.then((ret) => {
// Deal with the data
})
.catch((err) => {
// Deal with the error
});
如果要在单独的数组中获取数据:
const subscriptions = [{
teacher: 'john',
student: 'david',
course: 'math',
},
{
teacher: 'john',
student: 'david',
course: 'english',
},
{
teacher: 'matt',
student: 'max',
course: 'math',
},
];
Promise.all(subscriptions.map(x => Exam.find(x))
.then(([
find1,
find2,
find3,
]) => {
// Deal with the data
})
.catch((err) => {
// Deal with the error
});
// Explaination of :
.then(([
find1,
find2,
find3,
]) => {
// Deal with the data
})
// This is the equivalent
.then((rets) => {
const find1 = rets[0];
const find2 = rets[1];
const find3 = rets[2];
// Deal with the data
});
答案 2 :(得分:-1)
使用async
app.get('/',function(req,res){
var examsArray= [];
async.each(subscriptions,function(sub,callback){
Exam.find({teacher:sub.teacher,
student:sub.student,
course:sub.course},
function(err,exams){
if(err) return callback(error);
if(!err && exams){
examsArray.push(exams);
return callback(exams);
}
});
},
, function(err) {
if (err) { res.json(err); }
console.log("ALL FINISH");
if(!err){ res.json(examsArray); }
});
});
});