Handling Errors with promises for Mongodb in nodejs

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.

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?

Heres my code:

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

        }
    });
});

To pass in an id and to call my promise

const find = findOneAndUpdate(‘id goes here’);

find.then(

    success => console.log(success),
    

).catch(

    reason => console.log(reason)

)

Appreciate any help, thanks in advance !

Answer

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.');
    })
  });
};

Leave a Reply

Your email address will not be published. Required fields are marked *