Mongoose: Bug when passing undefined parameter in place of callback

Created on 9 Mar 2017  路  6Comments  路  Source: Automattic/mongoose

I have this:

function create(data, cb){
  return Prompt.create(data, cb);
}

If callback is undefined, I would expect it to return a Promise, instead, it's doing some really weird thing, where the first parameter is no longer recognized, and instead it's looking at the second parameter which is of course undefined, and tries to use the second parameter to instantiate the object which of course will fail validation.

confirmed-bug

Most helpful comment

Thanks for reporting, will be fixed with 4.8.7 :+1:

All 6 comments

@ORESoftware that's because in the node world, a callback takes 2 parameters: the error and the result. You should omit the callback parameter if you want to use promises.

For example:

return Prompt
  .create(data)
  .then(result => doStuffWithResult(result))
  .catch(error => handleError(error));

Right this relates to the other issue I opened, but this specifically targets the bug I was seeing when passing a null/undefined value, like so Model.create(data, null);

You're right, I can do this:

function create(data, cb){
 if(cb){
     return Prompt.create(data, cb);
 }
 else {
     return Prompt.create(data);
  }
}

but isn't it obvious that the problem actually lies with the Mongoose code, not mine? I shouldn't have to do the above check. Mongoose should be handling it. Is this not clear?

As I said, I am very familiar with the Node.js world.

I need to provide you the error that I see when passing a null/undefined value for callback. Please wait until I find it.

Fair enough, we can add a check to see if cb is undefined.

Yeah I can confirm this is a bug, I cannot figure out exactly why it's happening, but somehow I think you know what I am talking about.

The following screenshot shows that doc is defined, and that it has the fields "kind" and "value", yet I will get a validation error.

screenshot 2017-03-10 11 45 19

Just to summarize, when my code looks like this:

function create(data, cb){
  if(cb){
    Prompt.create(data, cb)
  }
  else{
    return Prompt.create(data);
  }
}

_then it works_

but when my code is like this:

function create(data, cb){
  return Prompt.create(data, cb);
}

_then it will fail, with bizarre results._

that is why I know there is a bug in the Mongoose library

If you need more information please let me know. thanks.

Thanks for reporting, will be fixed with 4.8.7 :+1:

Was this page helpful?
0 / 5 - 0 ratings