PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] How to deal with decimals in MongoDB v3.6

 August 13, 2022     database, decimal, mongodb, mongoose, schema     No comments   

Issue

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.


Solution

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.



Answered By - Stennie
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing