How can I get the query object inside a query?

Viewed 115

I have an object array which have query string. I loop through the query based on key. Query is working as expected. But the key value is not printing inside

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

Current Output is

outside A
outside B
inside B
inside B

Expected Output is

outside A
outside B
inside A
inside B

What mistake I am doing

1 Answers

Most probable cause of your problem is var keyword. Define keyQuery with let keyword so that it is block scoped.

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

If you don't declare keyQuery variable before using it, it will be declared globally with the var keyword.

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

Related