Reputation: 8490
What the best way to store monetary values on Mongoose?
I know in Java there is the type BigDecimal to handle all monetary values to avoid this problem.
There is any type in mongo or javascript to avoid it?
Upvotes: 1
Views: 5486
Reputation: 2173
Mongo data is stored as BSON (Binary JSON).
MongoDB adds some type on JSON. The complete list of these types can be found here, but there is no type specifically for money.
In short, for price, you can choose between storing it as a Number
(a Double
, to be precise) or as a String
. For most use cases, Number
should be more than enough.
If you need to deal with multiple currencies, I would recommend adding a separate field for storing the currency.
Upvotes: 0
Reputation: 900
Storing it as a Number
is fine, the issue is when you need to retrieve these values and perform operations.
Given the imprecision of floating-point math, I use this BigNumber library (https://www.npmjs.com/package/bignumber.js) to safely perform operations with floats.
Upvotes: 1
Reputation: 224335
Unless compelled for some reason, you want a type that exactly represents the values you use. This means you should:
If those are satisfied, you can use whatever format suits your purposes (e.g., is small in size, is built into the language, or is easy to convert between BSON and the format you use it in). One way to use binary floating-point to represent currency exactly is to use whole numbers of a unit, such as integer numbers of pennies instead of fractional numbers of dollars.
Note that merely storing and retrieving amounts of currency is fairly simple, and it can be done with integer formats or floating-point formats as long as you follow the guidelines above. However, calculating with currency cannot be done easily with either integer or floating-point arithmetic except for very simple calculations such as additions, subtractions, and multiplications by integers. For example, neither integer arithmetic nor binary floating-point arithmetic can exactly represent the unit price of an item sold three-for-a-dollar, nor can they can they generally calculate interest or percentage discounts without rounding errors. To handle such calculations, selecting a format is not enough; you must design the operations carefully.
Upvotes: 1