Browse Source

Extract lastErrorObject from the err argument if findAndModify fails

If findAndModify experiences an error, the obj argument to the callback
is undefined. Instead the lastErrorObject is attached to the err
argument, from where we extract it.

To not rely on the lastErrorObject ALWAYS being on the err object if
provided, we gracefully fall back to looking in the obj object and then
finally just return { n: 0 } if no lastErrorObject is found. This could
be a more strict algorihm, but this seems more future-proof.
saintedlama/travis-non-legacy
Thomas Watson Steen 11 years ago
parent
commit
649647c98e
  1. 4
      index.js
  2. 12
      tests/test-find-and-modify.js

4
index.js

@ -160,9 +160,11 @@ Collection.prototype.findAndModify = function(options, callback) {
upsert:!!options.upsert,
fields:options.fields
}, function(err, doc, obj) {
// If the findAndModify command returns an error, obj is undefined and the lastErrorObject
// property is added to the err argument instead.
// If the findAndModify command finds no matching document, when performing update or remove,
// no lastErrorObject is included (so we fake it).
(callback || noop)(err, doc, obj.lastErrorObject || { n: 0 });
(callback || noop)(err, doc, (err && err.lastErrorObject) || (obj && obj.lastErrorObject) || { n: 0 });
}]);
};

12
tests/test-find-and-modify.js

@ -63,7 +63,17 @@ insert([{
assert.ok(!err);
assert.equal(lastErrorObject.n, 0);
done();
// Correct error handling
db.a.findAndModify({
update: { $illigal: 1 }
}, function(err, doc, lastErrorObject) {
assert(err instanceof Error);
assert.equal(doc, null);
assert.equal(lastErrorObject.n, 0);
assert.equal(typeof lastErrorObject.err, 'string');
done();
});
});
});
});

Loading…
Cancel
Save