mongojs
mongojs copied to clipboard
remove() with one document to delete doesn't work when document not found with findOne()
var assert = require('assert');
var insert = require('./insert');
// Delete just one
insert([{
name:'Squirtle', type:'water'
}, {
name:'Starmie' , type:'water'
}, {
name:'Lapras' , type:'water'
}], function(db, done) {
// Remove just one
db.a.remove({type:'clouds'}, true, function(err) { // clouds instead of water
db.a.find({type:'water'}, function(err, docs) {
assert.equal(docs.length, 3); // AssertionError: 0 == 3
done();
});
});
});
If no record is found by findOne(), the parameter for remove is 'null' which removes all documents in current collection.
Possible solution in remove function:
Collection.prototype.remove = function() {
var self = this;
var callback = getCallback(arguments);
if (arguments.length > 1 && arguments[1] === true) {
this.findOne(arguments[0], function(err, doc) {
if (err) return callback(err);
if(!doc) return callback(null); // -> new code
self._apply(DRIVER_COLLECTION_PROTO.remove, [doc, callback]);
});
return;
}
this._apply(DRIVER_COLLECTION_PROTO.remove, arguments.length === 0 ? [{}, noop] : ensureCallback(arguments));
};
Nice catch! Published as 0.7.13
Maybe it would be better to return 0 when no document was removed. This is helpful when using safe mode.
Collection.prototype.remove = function() {
var self = this;
var callback = getCallback(arguments);
if (arguments.length > 1 && arguments[1] === true) {
this.findOne(arguments[0], function(err, doc) {
if (err) return callback(err);
if (!doc) return callback(null, 0);
self._apply(DRIVER_COLLECTION_PROTO.remove, [doc, callback]);
});
return;
}
this._apply(DRIVER_COLLECTION_PROTO.remove, arguments.length === 0 ? [{}, noop] : ensureCallback(arguments));
};
@4kochi Yes - it should do that. Just fixed that.