对猫鼬中获取的每个记录执行另一个查询?

时间:2020-02-01 12:20:08

标签: node.js mongodb mongoose

我正在使用Nodejs(12.14.1 LTS)和猫鼬(5.8.11)
考虑以下集合

collection1: {  
  // collection1 fields  
  rank_type : "some_value", 
  col1_price : "some_value",  
  col1_location : "some_value"   
}

collection2 : {  
  // collection2 fields  
  price : "some_value",  
  location: "some_value"  
}

我需要在单个查询中执行以下操作
1.根据某些条件从collection1中获取记录
2.在第一步中获取的每个记录上,都需要从collection2中获取记录

// explained in sudo code or some simplified way  
fetch from collection1 on basis of some condition {  
    loop on documents fetched from collection1 (docN) {  
      if(docN.rank_type === "high"){
         fetch documents from collection2 with conditions ( price : docN.col1_price, location:docN.col1_location)  
      } else if(docN.rank_type === "medium"){
         fetch documents from collection2 with some other conditions ( price : docN.col1_price, location:docN.col1_location, more_conditions_will_be_there)
      }
    }  
} 

我想以下面的方式输出

[
  {
    col1_id : _id_from_col1_document
    matched_details : [
      {document_from_col2},
      {document_from_col2}...
    ] 
  },
  ... other_records
]

我尝试的是

var cursor = collection1.find(some_condition).cursor();
cursor.on("data", doc => {
   if(doc.rank_type === "high"){
      collection2.find(some_conditions).then(result_documents =>{
         // did some loging
      })
   } if(docN.rank_type === "medium"){
      collection2.find(some_other_conditions).then(result_documents =>{
         // did some loging
      })
   }
});

在上面的代码中,我无法理解操作何时完成以及如何获得上述所需的输出。

0 个答案:

没有答案