Reputation: 482
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 ?
Upvotes: 6
Views: 4675
Reputation: 734
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
Upvotes: 2
Reputation: 312149
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.
Upvotes: 6