保存后更新Mongoose
Mongoose update after save
我缺少一些关于Mongoose保存函数回调的内容。我正在尝试插入一个新的交易,如果成功,请更新一个用户帐户。问题是,我相信,这会导致所有人都更新了最后一个人的金额。我要做的是在保存另一个文档后更新文档。
这是代码。请让我知道我做错了什么。提前谢谢。
//find all schedules
SchedModel.find({ Day_Of_Week: day }, null, null, function (err, Sched) {
if (!err) {
//iterate through what we find
for (var key in Sched) {
if (Sched.hasOwnProperty(key)) {
var val = Sched[key];
console.log("val : " + val);
var Sched_Descr = day || ' Sched Trans';
var this_trans = new TransModel({
mID: val.K_Id,
mDate: today,
mDescr: Sched_Descr,
mAmt: val.mAmt
});
//insert the new trans
this_trans.save(function (err, trans) {
if (!err) {
//when we insert new trans, get the update model
MyModel.findById(val.K_Id, function (err, Model) {
Model.Balance = Model.Balance + val.mAmt;
//save model, this update to the last in the list
Model.save(function (err) {
if (!err) {
console.log("updated");
} else {
console.log(err);
}
});
});
} else {
return console.log(err);
}
});
}
}
} else {
console.log(err);
};
});
Update:ES6的let
非常简单地解决了这个问题,只需在原始代码中用let
替换var
,它就可以工作了。
您的this_trans
和此类变量在for in循环的每次迭代中都不是唯一的。您可能想要将其封装在一个自执行匿名函数范围((function(){})()
)中
//find all schedules
SchedModel.find({ Day_Of_Week: day }, null, null, function (err, Sched) {
if (!err) {
//iterate through what we find
for (var key in Sched) {
(function(key){ // self-executing anonymous function scope
if (Sched.hasOwnProperty(key)) {
var val = Sched[key];
console.log("val : " + val);
var Sched_Descr = day || ' Sched Trans';
var this_trans = new TransModel({
mID: val.K_Id,
mDate: today,
mDescr: Sched_Descr,
mAmt: val.mAmt
});
//insert the new trans
this_trans.save(function (err, trans) {
if (!err) {
//when we insert new trans, get the update model
MyModel.findById(val.K_Id, function (err, Model) {
Model.Balance = Model.Balance + val.mAmt;
//save model, this update to the last in the list
Model.save(function (err) {
if (!err) {
console.log("updated");
} else {
console.log(err);
}
});
});
} else {
return console.log(err);
}
});
}
})(key);
}
} else {
console.log(err);
};
});
相关文章:
- Mongoose-在更新中删除数组元素
- Mongoose更新ref对象
- 检查文档是否已经存在,如果是则更新,否则创建新的Mongoose
- Mongoose创建一个文档,如果找不到指定的字段,则更新文档中的数组
- 保存后更新Mongoose
- MongoDB Mongoose使用数组保存或更新
- 如何在Mongoose中从多个数组更新数组内部的值
- 为任何更新查询增加 Mongoose 文档版本的简单方法
- 正在更新数据库中的对象?(Node.js w/Mongoose)
- 在Mongoose中更新子域数组而不获取父数组
- 使用Mongoose更新数组中的特定对象时出错
- Mongoose查找/更新子文档
- Mongoose更新子文档的子文档
- 使用mongoose更新数组
- 使用Mongoose更新嵌套对象
- 在MongoDB中使用mongoose更新数组中的对象
- 通过mongoose更新mongo内嵌套数组中的特定值
- mongoose更新嵌套值
- 如何使用 Mongoose 更新和读取 MongoDB 中的集合
- nodejs / mongoose 更新文档中的“多级”值 / 无法设置属性