Skip to content

fix: prevent CastError being triggered by literal NaN #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ class Double extends mongoose.SchemaType {
return new DoubleType(val.value);
}

// MongoDB allows storing NaNs in Number type attributes
// So testing for type number is truer to MongoDB behavior than testing for NaNs
const _val = Number(val);
if (isNaN(_val)) {
if (isNaN(_val) && typeof val !== 'number') {
throw new mongoose.SchemaType.CastError('Double',
val + ' is not a valid double');
}
Expand Down
32 changes: 32 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,38 @@ describe('Double', function() {
});
});

describe('NaNs', () => {
it('saves explicit NaNs', function() {
return co(function*() {
const schema = new mongoose.Schema({ val: Double });
const Model = mongoose.model('DoubleTest3', schema, 'doubletest3');

const doc = new Model({ val: NaN });
++doc.val;
yield doc.save();

assert.ok(yield Model.findOne({ val: { $type: 1 } }));
assert.ok(yield Model.findOne({ val: NaN }));
});
});

it('does not save implicit NaNs', function() {
return co(function*() {
const schema = new mongoose.Schema({ val: Double });
const Model = mongoose.model('DoubleTest4', schema, 'doubletest4');

const doc = new Model({ val: 'hi' });
++doc.val;
return doc.save().then(() => {
throw new Error('This should not save')
}).catch(e => {
assert.ok(true)
})
});
});
})


it('works in update', function() {
return co(function*() {
const doc = yield Model.create({ double: 1 });
Expand Down