gpt4 book ai didi

node.js - Mongoose : Trying to create a document in a callback,,其值位于外循环中

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:41 25 4
gpt4 key购买 nike

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

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

我想检查 doc 是否为空,如果是,则在数据库中输入默认值。如果返回了文档,则更新其属性。问题是我尝试保存的对象将 value[i] 作为其属性之一。但由于它是一个回调,因此我没有得到该特定值,因为它是在 for 循环中继续进行的。

我通过在模型创建过程中为所有不同值插入默认对象来解决这个问题,但是有没有办法在代码流中的此时执行此操作?

最佳答案

试试这个:

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 没有 block 作用域,这意味着 block 中引用的 v 变量被重用而不是重新创建。

当您立即使用该变量时(例如使用 model.findOne({ type: v}) ),这不是问题,但由于 query.exec 的回调函数将(可能)在循环完成后执行,回调中的 v 变量将仅包含循环中 v 的最后一个值。

通过使用 forEach,您每次都会创建一个新的 v 变量。

关于node.js - Mongoose : Trying to create a document in a callback,,其值位于外循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com