0

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?

  1. Because I am working with a different version of MongoDB
  2. Because I have just stored a decimal number in my DB without registering any serializers as instructed in the answer of the similar question And no error was thrown.

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.

YulePale
  • 6,688
  • 16
  • 46
  • 95

1 Answers1

1

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.

Stennie
  • 63,885
  • 14
  • 149
  • 175
  • Thank you. I don't fully understand why floating point numeric representation cannot accurately represent decimal values but I understand that if I need precision in calculating using decimals I am better off using Decimal128 type, which comes with Mongoose. – YulePale Dec 23 '18 at 07:56
  • 1
    @YulePale The links I included have more examples and background, but the general issue is that the binary representation used by the `Number` format cannot represent some fractional values. This introduces small accuracy errors that will accumulate. For example, try `3 * 0.1` in the `node` repl and you might be surprised to find the result is `0.30000000000000004`. Decimal128 is a standard encoding format ([IEEE 754 -2008](https://en.wikipedia.org/wiki/Binary_integer_decimal)) supporting up to 34 decimal digits with precision. With decimal values the result of `3 * 0.1` is `0.3`. – Stennie Dec 23 '18 at 21:25
  • I have read it.... plus with your comment I now understand. Happy Holidays and Thank You. – YulePale Dec 24 '18 at 10:44