LearnBoost/mongoose — Issue #617: Silent failure with invalid ObjectId in Model.findById().exec()
Author: jmar777
Created: 2011-11-17 16:05:29+00:00
State: open

When an invalid ObjectId is passed to Model.findById(), and the query is invoked with exec() (rather than passing a callback), the "Invalid ObjectId" error seems to be swallowed, and control is never returned to the invoking code ('complete' and 'error' events are never triggered, and an exception is not thrown).

**Test Script:**

```javascript
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Foo = mongoose.model('Foo', new Schema({ bar: String }));

mongoose.connect('mongodb://localhost/foo-store');

var scenarios = {

"valid-id": function() {
console.log('VALID ID SCENARIO');

Foo.findById('4ec307e70dd9840000000009').exec()
.on('complete', console.log.bind(null, 'COMPLETE'))
.on('error', console.log.bind(null, 'ERROR'));
},

"invalid-id-with-callback": function() {
console.log('INVALID ID WITH CALLBACK SCENARIO');

Foo.findById('invalid-object-id', function(err, doc) {
err ? console.log('ERROR', err) : console.log('COMPLETE', doc);
});
},

"invalid-id-with-exec": function() {
console.log('INVALID ID WITH EXEC SCENARIO');

Foo.findById('invalid-object-id').exec()
.on('complete', console.log.bind(null, 'COMPLETE'))
.on('error', console.log.bind(null, 'ERROR'));

// just waitin around...
setInterval(console.log.bind(null, "I'm thinking..."), 2000);
}
};

// prints: COMPLETE null
scenarios['valid-id']();

// prints: ERROR [Error: Invalid ObjectId]
setTimeout(scenarios['invalid-id-with-callback'], 1500);

// prints: I'm thinking... I'm thinking... I'm thinking...
setTimeout(scenarios['invalid-id-with-exec'], 3000);
```

**Output:**

```
VALID ID SCENARIO
COMPLETE null
INVALID ID WITH CALLBACK SCENARIO
ERROR [Error: Invalid ObjectId]
INVALID ID WITH EXEC SCENARIO
I'm thinking...
I'm thinking...
I'm thinking...
I'm thinking...
```

**Version Info:**

```
> node -v
v0.6.0
> npm ls | grep mongoose
└─┬ mongoose@2.3.11
```