Reputation: 7686
I am working with MongoDB v3.6.3.
I have seen a similar question that recieved a good answer. So why am I asking this question?
My MongoDB schema looks like this:
rating:{
type: Number,
required: true
}
So my question is, is there anything wrong with the way I have implemented this. Considering that I have already stored a decimal number in my DB. Is it okay to store decimal numbers with the current schema? Or is this a setup for errors in the future because I am missing a step?
Thank you.
Upvotes: 0
Views: 6302
Reputation: 65323
The Number
type is a floating point numeric representation that cannot accurately represent decimal values. This may be fine if your use case does not require precision for floating point numbers, but would not be suitable if accuracy matters (for example, for fractional currency values).
If you want to store and work with decimal values with accuracy you should instead use the Decimal128
type in Mongoose. This maps to the Decimal 128 (aka NumberDecimal
) BSON data type available in MongoDB 3.4+, which can also be manipulated in server-side calculations using the Aggregation Framework.
If your rating
field doesn't require exact precision, you could continue to use the Number
type. One reason to do so is that the Number
type is native to JavaScript, while Decimal128 is not.
For more details, see A Node.js Perspective on MongoDB 3.4: Decimal Type.
Upvotes: 1