diff --git a/lib/base-model.js b/lib/base-model.js index a724b9e..650c5b0 100644 --- a/lib/base-model.js +++ b/lib/base-model.js @@ -270,8 +270,16 @@ BaseModel.findById = function () { } var collection = BaseModel.db.collection(this._collection); - var query = { _id: this._idClass(args.shift()) }; + var id = args.shift(); var callback = this.resultFactory.bind(this, args.pop()); + var query; + + try { + query = { _id: this._idClass(id) }; + } + catch (exception) { + return callback(exception); + } args.unshift(query); args.push(callback); @@ -287,10 +295,18 @@ BaseModel.findByIdAndUpdate = function () { } var collection = BaseModel.db.collection(this._collection); - var query = { _id: this._idClass(args.shift()) }; + var id = args.shift(); var update = args.shift(); var callback = this.resultFactory.bind(this, args.pop()); var options = Hoek.applyToDefaults({ new: true }, args.pop() || {}); + var query; + + try { + query = { _id: this._idClass(id) }; + } + catch (exception) { + return callback(exception); + } collection.findAndModify(query, undefined, update, options, callback); }; @@ -299,7 +315,14 @@ BaseModel.findByIdAndUpdate = function () { BaseModel.findByIdAndRemove = function (id, callback) { var collection = BaseModel.db.collection(this._collection); - var query = { _id: this._idClass(id) }; + var query; + + try { + query = { _id: this._idClass(id) }; + } + catch (exception) { + return callback(exception); + } collection.remove(query, callback); }; diff --git a/test/lib/base-model.js b/test/lib/base-model.js index 11be933..5d00b11 100644 --- a/test/lib/base-model.js +++ b/test/lib/base-model.js @@ -559,6 +559,16 @@ lab.experiment('BaseModel Proxied Methods', function () { }); + lab.test('it catches the exception when id casting fails during findById', function (done) { + + SubModel.findById('NOTVALIDOBJECTID', function (err, result) { + + Code.expect(err).to.exist(); + done(); + }); + }); + + lab.test('it updates a single document via id', function (done) { var document = { name: 'New Name' }; @@ -573,6 +583,16 @@ lab.experiment('BaseModel Proxied Methods', function () { }); + lab.test('it catches the exception when id casting fails during findByIdAndUpdate', function (done) { + + SubModel.findByIdAndUpdate('NOTVALIDOBJECTID', {}, function (err, result) { + + Code.expect(err).to.exist(); + done(); + }); + }); + + lab.test('it updates a single document via id (with options)', function (done) { var document = { name: 'New Name' }; @@ -601,6 +621,16 @@ lab.experiment('BaseModel Proxied Methods', function () { }); + lab.test('it catches the exception when id casting fails during findByIdAndRemove', function (done) { + + SubModel.findByIdAndRemove('NOTVALIDOBJECTID', function (err, result) { + + Code.expect(err).to.exist(); + done(); + }); + }); + + lab.test('it removes documents via query', function (done) { SubModel.remove({}, function (err, result) {