I'm writing up a small project and part of it we are using NodeJS with MongoDB.
I'm receiving some issues with code that means the table is not updating when i want it to with one set of code. However, it updates when i use a similar bit of code that does not use async/await. I'm a bit unsure on the reason behind this? Wondered if anyone can lend a hand. I would prefer to use asynchronous to ensure that data is returned before it steps, which can be incosistent sometimes without asynchronous code.
collection.updateOne(
{UIN: assetData.UIN, Company: assetData.company},
{ $set: assetObject },
{ upsert: true },
(err, res) => {
if(err) throw err;
console.log("Updated")
})
Working code.
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;
}
})
Not working code.
Whole function
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")
})
}
I had a similar issue when trying to retrieve data where it worked when I just wrote fairly basic NodeJS, but did not like it when i started to include asychronous features.
As far as i can see the code is pretty much identical, but the bottom one does not seem to be working.
Thanks for any help!