Search code examples
node.jsmongodbmongoosemongoose-schema

How to save a Int value as Double in mongoose?


The project is 2 parts, 1 is NodeJS, 1 is Java. NodeJS is using mongoose, and I know in JavaScript and mongoose doesn't have int or float or double type, but Java does. It's a conflict of 2 technicals.

{
  number: {
    type: Number,
  }
}

I also try using @mongoosejs/double module. but it isn't working totally. When I save number = 1 it still saves the number as int32.

Another way: add 6 or 7 zero numbers after the decimal dot to force mongo to save it as double, but have a problem is when number is 0, it save number: 1e-7


Solution

  • Using mongoose schema you can install using npm I @mongoosejs/double in your project directory where node_modules folder is installed. Then in your model where you have defined your schema require on top const Double = require("@mongoosejs/double");, and finally in the schema object

    {
       number: {
          type: Double
       }
    }
    

    This should be able to save your type as Double in MongoDB. Here is a very useful resource https://www.npmjs.com/package/@mongoosejs/double