MongoDB type update from NumberLong to String
You can use valueOf() to get the value of a NumberLong as a javascript number value.
Casting NumberLong to Number :
NumberLong('5').valueOf() // 5
Then, you can then use easilly toString()
on your number to get the String value.
Casting NumberLong to String :
NumberLong('5').valueOf().toString() // "5"
The type NumberLong
exists for a reason, to handle huge numbers, similar to BigInt
on SQL. MongoDB relies on JavaScript which have at most 53 bits for integers, in ES6 the largest exact integral value is 253-1, or 9007199254740991, for this reason, "converting" from NumberLong to a simple string isn't as simple as the previous answer, here is an example:
var huge = NumberLong("987654321987654321");
huge.valueOf(); // 987654321987654300
huge.toString(); // NumberLong("987654321987654321")
huge.valueOf().toString(); // 987654321987654300
With this example, it is clear that JavaScript is rounding up the numbers while using valueOf()
, and lacking any sane response and documentation, I came with a workaround for this situation, using RegEx to remove any non numerical characters from the toString()
function:
huge.toString().replace(/[^\d]/g, '') // 987654321987654321
It isn't pretty, but it works, any other better solution is always appreciated. As a bonus fact, using JSON.stringify
converts the value into an object using the special char $
to represent the function to call while processing the value, the way MongoDB handles this issues while dealing with common day to day JSON objects:
JSON.stringify(huge) // {"$numberLong":"987654321987654321"}