Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal / Float in mongoose for node.js

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 ?

like image 339
Luc Avatar asked Apr 09 '11 14:04

Luc


People also ask

Can floats be decimal?

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.

What is the difference between decimal and double?

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.

Why mongoose is used in Node JS?

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.

Is decimal better than float?

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.


2 Answers

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.

like image 58
Andrew Orsich Avatar answered Sep 22 '22 00:09

Andrew Orsich


Yes you can use the Decimal128 type.

https://mongoosejs.com/docs/api.html#mongoose_Mongoose-Decimal128

like image 45
Muzaffar Mahmood Avatar answered Sep 20 '22 00:09

Muzaffar Mahmood