Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose / Mongodb update return value and error handling

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!! :)

like image 745
pupuupup Avatar asked Jul 01 '15 17:07

pupuupup


1 Answers

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.

like image 124
Eric Hartmann Avatar answered Sep 23 '22 21:09

Eric Hartmann