Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store large numbers in MongoDB with Node.js

I am using MongoDB with the native node driver and need to accurately store numbers that may be larger than the int maximum 2147483647. I will need to be able to increment the number as I am tracking usage. What are my options?

I am using Mongoose. The problem I am having is that when I $inc past 2147483647 it converts the number to a double. How can I force Mongoose to use the 64-bit long int NumberLong?

My schema looks like this

var schema = new Schema({
    ...
    usedBandwidth: {type: Number, min: 0, default: 0}
});

And my $inc looks like this

model.Account.update(
    {_id: this.account},
    {$inc: {usedBandwidth: this.size}},
    function (err, doc) {}
);
like image 425
respectTheCode Avatar asked Dec 23 '11 14:12

respectTheCode


1 Answers

You can now do this in Mongoose with the mongoose-long plug-in.

require('mongoose-long')(mongoose);
var SchemaTypes = mongoose.Schema.Types;
var schema = new Schema({
    ...
    usedBandwidth: {type: SchemaTypes.Long, min: 0, default: 0}
});
like image 163
JohnnyHK Avatar answered Oct 11 '22 08:10

JohnnyHK