biggora / caminte

Cross-db ORM for NodeJS
http://www.camintejs.com/
MIT License
1.08k stars 119 forks source link

Mongoose driver never calls remove callback if no record to delete was found #198

Open raffaele-clevermind opened 6 years ago

raffaele-clevermind commented 6 years ago

Using the mongoose driver, when calling the method remove with a filter that would delete 0 records the callback is never called. That's because of a piece of code in the mongoose adapter:

query.exec(function (err, data) {
        if (err) return cb(err);
        if (data) {
            var count = data.length || 0;
            for (var i in data) {
                if (typeof data[i] !== 'undefined') {
                    data[i].remove(function () {
                        if (--count === 0) {
                            cb(null, data);
                        }
                    });
                } else {
                    if (--count === 0) {
                        cb(null, data);
                    }
                }
            }
        } else {
            cb(null, data);
        }
    });

The remove method first executes a query with the required filters in order to get all the records to then delete them one by one and trigger the callback after removing the last one:

data[i].remove(function () {
  if (--count === 0) {
    cb(null, data);
  }
 });

The problem is that when no record is found "data" is an array with length 0, which means that the code will enter the "if (data) " condition but never start the for cycle, which means that the callback won't be triggered