I start my first test app on node.js / mongoDB / mongoose, this is a very simple app that aims to crate record in DB and retrieve them.
I create a model like:
var Car = new Schema({ brand : String, speed : Number, date : { type: Date, default: Date.now } });
This is working fine, except that I would like to be able to provide a float value for speed instead of the integer one. I gave a try to Decimal and Float but none of them are working. I did not find in the documentation either.
Any idea ?
If doing math with floats, you need to add a decimal point, otherwise it will be treated as an int. See the Floating point constants page for details. The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point.
Double (aka double): A 64-bit floating-point number. Decimal (aka decimal): A 128-bit floating-point number with a higher precision and a smaller range than Single or Double.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. MongoDB is a schema-less NoSQL document database.
Use decimals when precision matters, such as with financial calculations. Decimals can suffer from their own precision issues, but generally, decimals are more precise than floats.
I've searched a bit and found this article stating that for storing float values you must use Number
type. You can store any float value in speed
field.
Yes you can use the Decimal128
type.
https://mongoosejs.com/docs/api.html#mongoose_Mongoose-Decimal128
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With