使用 promises for Mongodb 在 nodejs 中处理错误

Handling Errors with promises for Mongodb in nodejs

我正在连接到名为 '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 goes here');

find.then(

    success => console.log(success),
    

).catch(

    reason => console.log(reason)

)

感谢任何帮助,提前致谢!

您需要在 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.');
    })
  });
};