Default "number" to double "Double" type

Right now, when I insert a new document from nodejs, number properties are inserted depending on the most fitting type, so 0 are inserted as Int32 but 0.1 as Double.

In mongo shell types are defaulted to Double. Is there any way to default all numbers to Double in mongodb nodejs driver? This is giving me some schema validation problems and don’t wall to fill my entire back-end with "new Double()"s.

Hello @Jorge_Fuentes, welcome to the MongoDB Community forum.

What you are saying is correct about the different types for the numbers with NodeJS driver. Can you tell how are you inserting the documents into the collection - I mean the code you are using to insert.

Hi @Jorge_Fuentes, welcome onboard!

You need to “cast” your value so they are actually Double in JS.

var Double = require("mongodb").Double;
var foo = Double(15) 

Thanks JS for not being a typed language :weary:.


An option is to use a ODM like Mongoose, where you can define a schema with field types. This might work.

Here is another possibility - you can define a custom number class which is used throughout the application. This will make sure that the number data is of one specific type (as needed for specific field or fields). This is not an unusual solution. I have studied such solutions for object-oriented applications (e.g., using Java) where a separate class, for example, to represent currency numbers.

Well, I was thinking about a config parameter under the driver options (if it exists), more than using a ODM or redoing part of the backend. As I already said, I don’t want to add Doubles all around the backend when I’m going to work with numbers. Just love to work with plain js.

mongo shell has, as per documentation (, Doubles as default, so I thought that the “convert to the most-fitting” was a driver thing, not a mongo one. If I have to redo part of the backend I prefer the casting thingy.

What I’m using to work with the database are the typical insertOne, updateOne, updateMany, etc… for example, one item with a property that starts at zero, I now use insertOne({...yadayada, prop: new Double(0)}), which I would like to be insertOne({...yadayada, prop: 0}). I just like to have the less conversion-code or less non-vanilla code as possible. I like to see it as plain as possible.

Thank you for your help!


@Jorge_Fuentes Did you ever find a solution? I’d like to do the same.

No, sorry. Just filled the backend with Double.

1 Like