This seems like it should be mind-numbingly simple, but I can’t figure it out. I want to basically insert 0 into a document, but as a Double value. The only way I can seem to do this is with a hack:
newId = Collection.insert({value: 0.1});
Collection.update(newId, {$inc: {$value: -0.1}});
I know that in dealing with mongo directly, you can specify types as you insert them, but that doesn’t seem to be possible within Meteor… or is it?
Well, there is decimal: option in simple schema, other than that I dont know
Never needed any other way or insert as specific type.
But I think it is JS way of handling numbers - they are all the same.
later the user can set to a value such as 2.8, but since in the database it’s an Int32, it drops the decimal.
this is strange!
I can certainly insert integers and later set them to doubles. are you sure you don’t have another problem elsewhere, perhaps with a schema enforcing package?
Except that, the first one “1” gets to be stored as Int32 by the get go. Makes no difference in how javascript interprets it though within the context of a meteor application.
But minimongo don’t provide constructors for Int, Long, and Double. Maybe they missed it, and we should raise it as an issue?
For your case:
I would assume that all numbers go into minimongo as a float/Double. To test it, after inserting, go to the mongo shell, find the document, and then check the field’s value’s type.
Weird. I did a test in Astronomy, defining a “number” type field. I was able to initially set it to 0 (it was Int32 in MongoDB), and then change it to 2.8 and it became a Double.
I’ll try again and go look at my code and see what’s up. Maybe I was imagining all of this…
Even if you try storing integer it will store float/double. There is always problem of precision, like for example 0.1 + 0.2 === 0.3 is false in JavaScript but not only in JS.
If you store number 0.0 it will definitely be 0.0 in a database, if you store 0 it will also be 0.0. However if that 0.0 number comes from some calculation it can contain non zero fractional part which I don’t know how will be stored in MongoDB.
And one more thing. I would rather not recommend using $inc operator for incrementing by non integer values. It’s even risky in JS alone (and other languages too).
If you need the number 0.0 in the UI you should just format it as a string: (0).toFixed(1);. It will give the "0.0" string.