我正在编写一个小项目,其中的一部分是我们将NodeJS与MongoDB结合使用。
我收到一些代码问题,这意味着当我希望使用一组代码来更新表时,该表没有更新。但是,当我使用不使用异步/等待的类似代码时,它会更新。我不确定这背后的原因吗?想知道是否有人可以伸出援手。我更喜欢使用异步来确保在执行步骤之前返回数据,这有时可能会令人生厌,而没有异步代码。
collection.updateOne(
{UIN: assetData.UIN, Company: assetData.company},
{ $set: assetObject },
{ upsert: true },
(err, res) => {
if(err) throw err;
console.log("Updated")
})
工作代码。
await collection.updateOne(
{ UIN: assetData.UIN, Company: assetData.company },
{ $set: assetObject },
{ upsert: true })
.then( err => {
if (err){
console.log( 'err', err)
return false;
} else {
console.log("Document updated")
return true;
}
})
无法正常工作的代码。
整体功能
async function assetUpdate(client, assetData){
//Updating the values on the asset table.
const assetObject = {
UIN: assetData.UIN,
Type: assetData.type,
Name: assetData.name,
Company: assetData.company,
Location: assetData.location
}
const collection = client.db("Cluster0").collection("Asset");
collection.updateOne(
{ UIN: assetData.UIN, Company: assetData.company },
{ $set: assetObject },
{ upsert: true },
(err, res) => {
if(err) throw err;
console.log("Updated")
})
}
我刚写了相当基本的NodeJS时尝试检索数据时会遇到类似的问题,但是当我开始包含异步功能时却不喜欢它。
据我所知,代码几乎完全相同,但最底层的代码似乎无法正常工作。
谢谢你的帮助!
这是将async
/await
与返回a的函数配合使用的正确方法Promise
:
try {
const result = await collection.updateOne({
UIN: assetData.UIN,
Company: assetData.company
}, {
$set: assetObject
}, {
upsert: true
});
console.log('Document updated');
} catch (err) {
console.error(err);
throw err;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句