我在使用nodejs和mongoose的代码中遇到问题。我有一个应该从mongodb(book.findOne)获取书籍的函数,然后使用第二个查询(updateMany)更新它们。 问题是UpdateMany查询在获取书籍之前执行..所以我的数组保持为空并且没有任何更新。 我知道node.js是异步的,但我怎么能解决这个问题?
function UpdateBulk(completeValidBooks){
var existingRowsInDb = [];
completeValidBooks.forEach(function(currentBook) {
book.findOne({'ISIN': currentBook.ISIN },
function(error, result) {
existingRowsInDb.push(result);
});
});
book.updateMany(existingRowsInDb, (err,docs) => {
err ? console.log(err) : console.log(`updated ${docs.length}`);
});
}
答案 0 :(得分:1)
使用诺言你可以这样做:
function UpdateBulk(completeValidBooks) {
GetExistingRows(completeValidBooks).then((existingRowsInDb) => {
book.updateMany(existingRowsInDb, (err, docs) => {
err ? console.log(err) : console.log(`updated ${docs.length}`);
});
})
}
function GetExistingRows(completeValidBooks) {
return new Promise((resolve, reject) => {
var existingRowsInDb = [];
completeValidBooks.forEach((currentBook) => {
book.findOne({
'ISIN': currentBook.ISIN
}, (error, result) => {
existingRowsInDb.push(result);
});
});
resolve(existingRowsInDb);
})
}
使用回调你可以这样做:
function UpdateBulk(completeValidBooks) {
GetExistingRows(completeValidBooks, (existingRowsInDb) => {
book.updateMany(existingRowsInDb, (err, docs) => {
err ? console.log(err) : console.log(`updated ${docs.length}`);
});
})
}
function GetExistingRows(completeValidBooks, callback) {
var existingRowsInDb = [];
completeValidBooks.forEach((currentBook) => {
book.findOne({
'ISIN': currentBook.ISIN
}, (error, result) => {
existingRowsInDb.push(result);
});
});
callback(existingRowsInDb);
}