簡體   English   中英

在foreach中的mongoose find()

[英]mongoose find() inside a foreach

我想根據數組中的某些條件查找文檔,例如:

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庫嗎? 我認為此查詢有更好的方法,不需要循環

如果要獲取與數組條目之一匹配的所有文檔:

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
});

您應該選擇使用or運算符,而不是循環選擇:

Exam.find().or(subscriptions).then(docs => { 
/*logic here*/ 
})
.catch(error => { 
/*error logic here*/ 
})

使用異步

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); }
      });
    });
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM