在Node.js中使用MongoDB的Promise处理错误 [英] Handling Errors with promises for Mongodb in nodejs

查看:41
本文介绍了在Node.js中使用MongoDB的Promise处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am connecting to a mongodb collection named 'Users' which has the _id field. I am attempting to find and update an existing document in the database using mongodb findOneAndUpdate() method. To begin with i pass in the id as an argument to my function which works fine. The document does indeed update using the $set method but still outputs the resolve when it should catch the reject when there is no existing document.

我如何应允地抓住错误.我认为这里的问题是,除非将其传递给变量,否则我不会从mongodb api得到任何响应.但是仍然知道这一点,当没有与查询匹配的现有文档时,如何捕获错误?

How do i catch the error with a promise. I think the issue here is that i am not getting any response back from the mongodb api unless i pass it to a variable. However still knowing this, how do i catch the error when there is no existing document that does not match the query?

这里是我的代码:

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并称呼我的诺言

To pass in an id and to call my promise

const find = findOneAndUpdate('id go here');

const find = findOneAndUpdate('id goes here');

find.then(

    success => console.log(success),
    

).catch(

    reason => console.log(reason)

)

感谢您的帮助,谢谢!

推荐答案

您需要在mongodb的findOneAndUpdate中指定一个回调.

You need to specify a callback in mongodb's 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.');
    })
  });
};

这篇关于在Node.js中使用MongoDB的Promise处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆