7

I am a little confused about the return value of Mongoldb update and how should I handle error with it.

I am using Node.js, Express.js and Mongoose.js as my Mongodb driver

As I look through many tutorial, the only way of error handling I saw is ...

Example: A simple user schema .. and I want to update telephoneNumber

Users 

{ 
  email : [email protected],
  telephoneNumber : 123456
}

Example of error handling written in node.js that many tutorial taught me

 Users.update({email: [email protected]}, {'$set': {telephoneNumber : 654321}, function(err, result){
      if(err){
           //err
      }else if(!result){
           //update not success
      }else{
           //update success
      }
 });

but as I look through Mongodb documentation, I found out that update return WriteConcern value, which return something like this

 {
      "ok" : 1,             // update with no err
      "nModified" :1,        // successfully update 1 user
      "n" : 1               // found 1 
 }

So my question is, should I handle my error like this instead, so I would know more about the failures of update...

  Users.update({email: [email protected]}, {'$set': {telephoneNumber : 654321}, function(err, result){
      if(err || result.ok === 0){
           //err
      }else if(result.nModified === 0){
           //update fail
      }else if(result.n === 0){
           //could not be found 
      }else{
           //update success
      }
 });

Is this a bad approach to update handling in mongoose/mongodb?

Thanks!! :)

1 Answer 1

5

Here is how we handle mongoose/mongodb errors. They might be errors like "that value already exists" Or similar issues.

First in the error block of the mongoose call we add:

if (err) {
    return res.status(400).send({
                    message: errorHandler.getErrorMessage(err,req,res)
                });
}

Which calls a 'getErrorMessage' function which is defined in our errorHandler file, which might call the unique error message function. We also log the errors in our mongo database under a separate collection.

exports.getErrorMessage = function(err,req,res) {
    var message = '';
    if (err.code) {
        switch (err.code) {
            case 11000:
            case 11001:
                message = getUniqueErrorMessage(err);
                break;
            default:
                message = 'Something went wrong. We have logged this issue and will correct';
        }
    } else {
        for (var errName in err.errors) {
            if (err.errors[errName].message) message = err.errors[errName].message;
        }
    }
    //log the error to Mongo
    ErrorLog.create(err,req,res);
    return message;
};

var getUniqueErrorMessage = function(err) {
var output;

try {
    var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
    output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists';

} catch (ex) {
    output = 'Unique field already exists';
}
return output;

};

Hope that helps, let me know if I can clarify anything.

Sign up to request clarification or add additional context in comments.

3 Comments

Thankyou for your help :) i got some questions though . So if I handle error like this , this mean I can handle error like the first example on my post ? If so , will this error handling work for every mongodb / mongoose operations (such as update, find, save ,etc)? Thanks:)
Oh yea , and 1 more thing , what if I want to know did the update operation ever updated any of the document. Should I still use result.nModified > 0 to check if any document were updated?
Yes, you can do that, to make sure the update happened.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.