mongoose-double
Importing
// Using Node.js `require()`
const Double = require('@mongoosejs/double');
// Using ES6 imports
import Double from '@mongoosejs/double';
Examples
It ensures your numbers are always stored as doubles in MongoDB
const schema = new mongoose.Schema({ val: Double });
const Model = mongoose.model('Double', schema);
const doc = new Model({ val: 41 });
// `doc.val` will be an object, not a number, but you can still use it as
// a number
assert.ok(doc.val instanceof mongoose.Types.Double);
assert.ok(doc.val instanceof Number);
assert.equal(typeof doc.val, 'object');
++doc.val;
return doc.save().
then(function() {
return Model.findOne({ val: { $type: 'double' } });
}).
then(function(doc) {
assert.ok(doc);
assert.equal(doc.val, 42);
}).
then(function() {
return Model.findOne({ val: { $type: 'int' } });
}).
then(function(doc) {
assert.ok(!doc);
});
It bypasses the MongoDB driver's integer coercion
This plugin is useful because the MongoDB Node.js driver
will store the JavaScript number 5.01
as a double, but it will store 5
as an integer. There is currently no option to opt out of this behavior
in the MongoDB driver.
const schema = new mongoose.Schema({ val: Number });
const Model = mongoose.model('Number', schema);
return Model.create([{ val: 5.01 }, { val: 5 }]).
then(function() {
return Model.findOne({ val: { $type: 'double' } });
}).
then(function(doc) {
assert.ok(doc);
assert.equal(doc.val, 5.01);
}).
then(function() {
return Model.findOne({ val: { $type: 'int' } });
}).
then(function(doc) {
assert.ok(doc);
assert.equal(doc.val, 5);
});
Changelog
0.2.0 / 2019-11-10
- feat: add support for comparison query selectors
$gt
,$lt
, etc. #8 w33ble - feat: remove
valueOf()
and addtoBSON()
to support using arithmetic operators with doubles #7 - fix: add Mongoose as peerDependency and pin minimum version 5.7.9
0.1.2 / 2018-10-16
- chore: add homepage to npm
- docs: add examples.md
0.1.1 / 2018-05-07
- docs: clean up example code formatting
0.1.0 / 2018-05-01
- feat: add mongoose 5 support, re: Automattic/mongoose#5813
0.0.1 / 2012-11-16
- initial release