【问题标题】:Handling Errors with promises for Mongodb in nodejs在 nodejs 中使用对 Mongodb 的 Promise 处理错误
【发布时间】:2021-06-05 18:40:43
【问题描述】:

我正在连接一个名为“Users”的 mongodb 集合,该集合具有 _id 字段。我正在尝试使用 mongodb findOneAndUpdate() 方法在数据库中查找和更新现有文档。首先,我将 id 作为参数传递给我的函数,它工作正常。该文档确实使用 $set 方法进行了更新,但是当它应该在没有现有文档时捕获拒绝时仍然输出解析。

我如何通过 promise 捕获错误。我认为这里的问题是我没有从 mongodb api 得到任何响应,除非我将它传递给一个变量。但是仍然知道这一点,当没有与查询不匹配的现有文档时,我如何捕获错误?

这是我的代码:

let findOneAndUpdate = ( (id) => {

return new Promise( (resolve, reject) => {
       
        if(id){
            db.collection('Users').findOneAndUpdate({_id: new ObjectID(id)}, {
                $set: {
                    name: 'Andrea',
                    age: 1,
                    location: 'Andromeda'
                    }
                }
            );

            resolve('Document matching the _id has been successfully updated.')

        }else{

            reject(new Error('Unable to find the _id matching your query'));          

        }
    });
});

传入一个id并调用我的promise

const find = findOneAndUpdate('id 在这里');

find.then(

    success => console.log(success),
    

).catch(

    reason => console.log(reason)

)

感谢任何帮助,在此先感谢!

【问题讨论】:

    标签: node.js mongodb error-handling es6-promise


    【解决方案1】:

    需要在 mongodb 的 findOneAndUpdate 中指定回调。

    https://github.com/mongodb/node-mongodb-native#user-content-update-a-document

    let findOneAndUpdate = (id) => {
      return new Promise((resolve, reject) => {
        if (!id) {
          reject(new Error('No id specified'));
        }
        db.collection('Users').findOneAndUpdate({
          _id: new ObjectID(id)
        }, {
          $set: {
            name: 'Andrea',
            age: 1,
            location: 'Andromeda'
          }
        }, function(err, result) {
          if (err) {
            return reject(err);
          }
          resolve('Document matching the _id has been successfully updated.');
        })
      });
    };
    

    【讨论】:

    • 感谢您的快速回复。首先处理错误是个好主意。指定回调有效,但我只是想补充一点,mongodb api 的行为方式并不像我认为的那样。回调 (err) 收到一个 null 值,所以我不得不使用 result.value === null 来输出拒绝语句。我这里有什么遗漏吗?
    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 2021-05-09
    • 2022-08-18
    • 2015-06-19
    • 1970-01-01
    • 2014-12-15
    • 2014-06-21
    • 2019-02-17
    相关资源
    最近更新 更多