NodeJS mongo await/async functions

Viewed 970

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!

2 Answers

Here is the proper way to use async/await with a function which returns 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;
}

You need to return a Promise for your query since async/await works on amalgamation of Promises:

var updatePromise = () => {
       return new Promise((resolve, reject) => {
        collection.updateOne({
            UIN: assetData.UIN,
            Company: assetData.company
        }, 
        { $set: assetObject} , 
           {upsert: true});

           });
       });

 //await myPromise
 var result = await updatePromise();
Related