如何在查询中获取查询对象?

时间:2020-05-28 11:39:14

标签: javascript node.js mongodb

我有一个带有查询字符串的对象数组。我根据关键字循环查询。查询正在按预期方式工作。但是关键不是在里面打印

query = { 
   A: { code: { '$in': ['A'] }},
   B: { code: { '$in': ['B'] }} 
}

for (keyQuery of  Object.keys(query)) {
   console.log("outside",keyQuery );

   testcollection
      .find(query[keyQuery],{_id:0})
      .then(data => {
          console.log("inside",keyQuery);
      });
}

当前输出为

outside A
outside B
inside B
inside B

预期输出为

outside A
outside B
inside A
inside B

我在做什么错

1 个答案:

答案 0 :(得分:2)

最可能的问题原因是var关键字。使用关键字keyQuery定义let,以使其成为块作用域。

for (let keyQuery of  Object.keys(query)) {
   // code
}

如果在使用变量之前未声明keyQuery,它将使用var关键字进行全局声明。

const testCollection = {
  find() {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(2), 2000);
    });
  }
}

const query = { 
   A: { code: { '$in': ['A'] }},
   B: { code: { '$in': ['B'] }} 
}

for (let keyQuery of  Object.keys(query)) {
   console.log("outside",keyQuery );

   testCollection
      .find()
      .then(data => {
          console.log("inside",keyQuery);
      });
}