Search code examples
node.jsmongoosemongoose-schema

Mongoose - Increment very large number


I want to save a very large 16 digit number in my db like below:

{ "_id" : ObjectId("5eb550aae41d233f1058efb0"), "id" : 1, "referenceId" : 100000000000000000, "__v" : 0 }
and increment its value by 1. But for some reason, the number I have saved in db doesnt increment.
This is what I have done:

    return new Promise((resolve, reject) => {
    // Incrementing the only document in 'referenceIds' collection by 1
    ReferenceId.findOneAndUpdate(
        { id: 1 },
        { $inc: { referenceId: 1 } }
    ).then(res => {
        // If no document found, creating new one.(This is a one time activity)
        if (!res) {
            let referenceIdDoc = new ReferenceId({
                id: 1,
                referenceId: 100000000000000000
            })
            referenceIdDoc.save()
                .then(res => {
                    resolve(res.referenceId);
                })
                .catch(err => {
                    reject(err);
                });
        } else {
            resolve(res.referenceId);
        }
    }).catch(err => {
        reject(err);
    });
});  

But the reference that is saved in db is as follows:

{
"_id" : ObjectId("5eb554cb80a31d3670afddcb"),
"id" : 1,
"referenceId" : 1e+17,
"__v" : 0
}  

And after the incrementing the 'referenceId' in the above code snippet I have given, 'referenceId' remains the same. i.e 100000000000000000.

How can I save and increment very big integers like 100000000000000000 in mongodb using NodeJs and Mongoose?

Can anyone please help me out here? I have been stuck on this issue for hours. Any kind of help would be appreciated. Thanks

UPDATE:

I have used mongoose-long npm module to deal with very large integers and made the following changes in my application:

const mongoose = require("mongoose");
require('mongoose-long')(mongoose);

let SchemaTypes = mongoose.Schema.Types;

const ReferenceId = mongoose.Schema({
  id: {
    type: Number,
    required: true
  },
referenceId: {
    type: SchemaTypes.Long,
    required: true
}
})

module.exports = mongoose.model("ReferenceId", ReferenceId);

. The value is getting incremented as well as expected. Like below:

{
"_id" : ObjectId("5eb55c2d83d44f1f2864ff86"),
"id" : 1,
"referenceId" : NumberLong(100000000000000005),
"__v" : 0
}  

However, in my NodeJs application, I'm not getting the actual value of 'referenceId'. I get the following Object:

{_bsontype: "Long", low_: 1569325061, high_: 23283064}  

Can anyone please tell me how I can get the actual value from db?


Solution

  • You can use the [mongoose-long][1] npm package while working with mongoose. You can get the value into your variable. Add 1 and then update the mongoose object. Let me know if it works for you.

    var mongoose = require("mongoose");
    let Schema = mongoose.Schema;
    require("mongoose-long")(mongoose);
    mongoose.connect("mongodb://localhost/appsyoda", { useNewUrlParser: true });
    
    var db = mongoose.connection;
    db.on("error", console.error.bind(console, "connection error:"));
    db.once("open", function() {
        // we're connected!
        console.log("connected");
    });
    
    var SchemaTypes = mongoose.Schema.Types;
    var partSchema = new Schema({ someLong: SchemaTypes.Long });
    
    var Part = db.model("Part", partSchema);
    
    var part = new Part({ someLong: "100000000000000005" });
    
    var Long = mongoose.Types.Long;
    part.someLong = part.someLong.add(Long.fromString("1"));
    console.log(part.someLong.toString());
    part.save();
    console.log("part " + part.someLong);
    

    Crux of the code is .toString() function of Long. Check http://mongodb.github.io/node-mongodb-native/api-bson-generated/long.html this link for details.