Mongoose:尝试在callback中创build一个文档,其值在外部循环中

我最近偶然发现了一个问题,下面是我的代码:

var v, query; for(var i=0; i<values.length; i++) { v = values[i]; query = model.findOne({type:v}); query.exec(function(err, doc) { if(doc == undefined) { var m = new model({type:v, count:0}); // but the 'v' above is not the values[i] in the for loop // code to save comes here } else { doc.count++; // update code comes here } }); } 

我想检查文档是否为空,如果是,请在数据库中input默认值。 如果有一个文档返回,然后更新它的属性。 问题是,我试图保存的对象具有值[我]作为它的一个属性。 但是由于这是一个callback函数,我没有得到那个特殊的值,因为它在for循环中继续。

我通过在模型创build过程中为所有不同的值插入一个默认对象来解决这个问题,但是在代码stream的这一点上有办法做到这一点吗?

试试这个:

 values.forEach(function(v) { var query = model.findOne({type:v}); query.exec(function(err, doc) { if(doc == undefined) { var m = new model({type:v, count:0}); // but the 'v' above is not the values[i] in the for loop // code to save comes here } else { doc.count++; // update code comes here } }); }); 

它不适for循环的原因是因为Javascript没有块范围,这意味着块中引用的vvariables被重用而不是重新创build。

当你立即使用这个variables的时候(比如model.findOne({ type: v}) ,这并不是问题,但是因为query.exec的callback函数在循环结束后可能会执行,所以callback函数中的variablesv将仅包含循环中v的最后一个值。

通过使用forEach ,您每次都会创build一个新的vvariables。