mongojs icon indicating copy to clipboard operation
mongojs copied to clipboard

remove() with one document to delete doesn't work when document not found with findOne()

Open sharkboy1976 opened this issue 13 years ago • 3 comments


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));
};

sharkboy1976 avatar Aug 12 '13 13:08 sharkboy1976

Nice catch! Published as 0.7.13

mafintosh avatar Aug 12 '13 13:08 mafintosh

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 avatar Aug 12 '13 20:08 4kochi

@4kochi Yes - it should do that. Just fixed that.

mafintosh avatar Aug 12 '13 20:08 mafintosh