【发布时间】:2019-01-22 12:57:42
【问题描述】:
我正在使用 mongoose.save() 更新 2 个文档,但我认为我这样做的方式并不安全,据我所知我需要使用异步来确保所有文档都正在执行
// array containing the 2 documents from db
let schedules
let newItem = {
isActive: room.isActive,
name: room.roomname
};
// adding new items to nested array
schedules[0].rooms.push(newItem);
schedules[1].rooms.push(newItem);
// saving / updating documents
var total = schedules.length,
result = [];
function saveAll() {
var doc = schedules.pop();
doc.save(function(err, saved) {
if (err) throw err; //handle error
result.push(saved);
if (--total) saveAll();
else {
// all saved here
res.json(result);
}
});
}
saveAll();
任何解释如何正确地做到这一点
【问题讨论】:
标签: node.js express asynchronous mongoose async-await