6

I'm working on a new project and I try to figure out why when Mongoose save my model, instead of having an integer, I got a Double.

Ex. {myId: 12345678} become {myId: 12345678.0}​

My schema contains this:

{
 myId: {
  type: Number
 }
}

Mongoose version: 5.x Node: 10.x

Any idea ?

2 Answers 2

6

The Number schema type is floating point. If you want to store a number as an integer, you can use the mongoose-int32 plug-in:

var Int32 = require('mongoose-int32');
const schema = new mongoose.Schema({
  myId: {
    type: Int32
  }
});

If you need 64-bit integer support, use the mongoose-long plug-in.

Sign up to request clarification or add additional context in comments.

7 Comments

why mongoose itself doesn't give that date type?
@Ashish I'm also surprised that data type isn't not part of Mongoose itself. Especially as the author of the plug-in is one of the main Mongoose developers.
Thank you for your message. Meanwhile, I used this library: mongoose-long npmjs.com/package/mongoose-long It works great too :)
@Vincent Both work for integers; mongoose-long is 64-bit and mongoose-int32 is 32-bit.
It's so irony that neither mongodb or mongoose provides int type by default
|
2

Instead of additional npm package overhead, it's recommended to use such getter/setter in the Schema Types.

var numberSchema = new Schema({
  integerOnly: {
    type: Number,
    get: v => Math.round(v),
    set: v => Math.round(v),
    alias: 'i'
  }
});

Therefore, CRUD operations related to field of Number Schema Type will cast to Int32 in Mongodb.

More info can be found in Mongoose v5.8.9 Schema Types documentation

1 Comment

This solution did not work for me. I don't want to use Plugins either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.