Mongo SchemaType Getter Setter Function is not working

To anyone who is getting the same problem with getter function while rounding of price from MongoDB, so you can do the same as me :

const courseSchema = new mongoose.Schema({

name: {

    type: String,

    lowercase: true,

},

author: String,

price: {

    type: Number,

    get: v => Math.round(v),

    set: v => Math.round(v),

}

},{

toObject: { getters: true, setters: true },

toJSON: { getters: true, setters: true },

runSettersOnQuery: true

})

By adding

{ toObject: { getters: true, setters: true },

toJSON: { getters: true, setters: true },

runSettersOnQuery: true}

you enable getter and setter function in mongo
for me, the setter was working fine but the getter was not rounding the number, it was giving the same result of DB which was “11.9”.

Hope this will help you

2 Likes

Thanks for this. Same issue. Your fix allowed me to keep moving.