Nodejs,Express和Mongo:循环中的回调函数被忽略

时间:2016-10-25 14:08:52

标签: node.js mongodb loops express callback

我对NodeJS,Mongo和Express都很陌生,所以我为一个看似简单的问题道歉。

我想要比较的传入数据具有以下结构:

type Animal struct { kingdom string phylum string family string } var wolf = Animal{"Animalia", "Chordata", "Canidae"} var tiger = wolf tiger.family = "Felidae"

我正在尝试做的是,当数据进入时,循环遍历数组,选择每个键,在mongo中搜索“assets”集合以查找与该键匹配的文档,如果匹配,则比较{传入数据的value1}与mongo中找到的匹配的{valueStored}。

这是我的代码:`

key1: {value1}
 key2: {value2}
 key3: {value3}

`

当我运行代码时,它会打印以下内容:

app.all('/css', function(req, res, next) {
  if (req.url === "/favicon.ico"){
    res.sendStatus(200);
    res.end();
  }

  var time = Math.floor(new Date() / 1000);
  var cssFiles = req["body"]["css_information"]["css"];
  var collection = database.collection("assets");
  for (key in cssFiles){
    if (cssFiles.hasOwnProperty(key)){
      console.log("key outside find(): "+key);
      // key above is cycling through properly, but key inside find() is stuck on last one
      // so it isn't cycling through properly, and only searches for the last one everytime.
      database.collection("assets").find({"path":key}).sort({"timestamp_changed" : -1}).limit(1).toArray(function (err, docs){
        console.log("--docs inside find(): "+JSON.stringify(docs[0], null,4));
        console.log("key inside find(): "+key);
        if (docs[0] != null){
          // console.log(JSON.stringify(docs[0]["css"], null, 4));
          var lastCSS = docs[0]["css"];
          if(lastCSS !== cssFiles[key]){
            database.collection("assets", function(err, col3) {
              collection.updateOne({"parent":"css", "timestamp_changed":time, "path":key,"css":cssFiles[key]},
                            {$set:{"path":key} },
                            {upsert: true, multi: false});
              // database.close();
            });
          }else{
          console.log("no changes");
          //end of if lastCSS === cssFiles[key] statement
          }
        }else{
          console.log("Key: "+key);
          database.collection("assets", function(err, col3) {
            collection.updateOne({"parent":"css", "timestamp_changed":time, "path":key,"css":cssFiles[key]},
                        {$set:{"path":key} },
                        {upsert: true, multi: false});
            });
        //end of if (doc[0] != null) statement  
        }
      //end of find() callback
      });  
    }else{
      console.log("cssFiles ¬hasOwnProperty(key)");
    }
//end of for loop
  }
res.status(200).json({data:"RETURN STATUS"}).end();
});

如何让find()代码使用正确的密钥而不是每次都卡在最后一个密钥上?或者我完全错误地接近了这个?

1 个答案:

答案 0 :(得分:1)

由于JavaScript是异步的,因此每个查询都在循环结束后执行,因此使用最后一个键(每次循环执行时都会更改)。

哟必须复制你的密钥并使用副本运行查询:

let localKey = key;
database.collection("assets").find({"path":localKey}).sort( <etc with localKey instead of key>