Large numbers interrupt underscore.js _.contains

When debugging the callback, mongooseI found that either underscore.js or the JavaScript language itself seems to have problems with large numbers.

In the example below, I save a small number and a string containing the ObjectId of mongoose (24-digit number) to show the problem as clearly as possible.

var users = ["32", "300000000000000000000002"];
alert(_.contains(users, "32")); // true
alert(_.contains(users, (32).toString())); // true
alert(_.contains(users, "300000000000000000000002")); // true
alert(_.contains(users, (300000000000000000000002).toString())); // false - wait wat ?

My question, of course, is how to make the last call true?

I would prefer not to convert the array usersto an array of numbers, because (1) the array can be huge in a production context and (2) I may need to perform other operations on the array.

+4
source share
2 answers

The problem was that I get an input string that is automatically converted to a number (via the library). Therefore, I only had to make the "foreign key" a smaller number. As a result, I created a user number auto-generation function to get around this problem:

var autoIncrement = require('mongoose-auto-increment');
var address = require('./Address');
var connection = mongoose.createConnection(address.mongo());
autoIncrement.initialize(connection);

var UserSchema = new mongoose.Schema({ /* property definitions */});
mongoose.model('User', UserSchema);

UserSchema.plugin(autoIncrement.plugin, {
    model: 'User',
    startAt: 10000001
});

As a result, I had to change the link mechanism:

var GroupSchema = new mongoose.Schema({
    users: [{type: Number, ref: 'User'}],
    /* other property definitions */
});
+1
source

The latter returns "3e+23"which is not equal"300000000000000000000002"

+3
source

Source: https://habr.com/ru/post/1617731/


All Articles