【问题标题】:NodeJS mongo await/async functionsNodeJS mongo 等待/异步函数
【发布时间】:2020-09-23 07:07:53
【问题描述】:

我正在编写一个小项目,其中一部分我们使用 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 时,我在尝试检索数据时遇到了类似的问题,但当我开始包含异步功能时不喜欢它。

据我所知,代码几乎相同,但底部的代码似乎不起作用。

感谢您的帮助!

【问题讨论】:

    标签: node.js mongodb mongoose async-await


    【解决方案1】:

    这是使用async/await 与返回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;
    }
    

    【讨论】:

    • 这很有效,谢谢。它没有跟随我的函数中的 .then() 的原因是什么?我假设这等待响应,如果有错误会捕获并输出它。再次感谢
    • 那是因为.then() 的回调不是(err, res) => ... 而是res => ...,如果你想处理Promise 抛出的错误而没有async/await 语法是@ 987654331@
    【解决方案2】:

    您需要为您的查询返回一个 Promise,因为 async/await 用于合并 Promise:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 2019-07-20
      • 2023-03-13
      • 2020-06-03
      相关资源
      最近更新 更多