Is it possible to disable automatic type casting for Mongoose SchemaTypes?

Viewed 2187

For a model with this Schema...

{ name: { type: String } }

...the following automatically casts the provided value to a string instead of enforcing the type:

document.name = 2; document.validate(err => { // Err is null, document.name === '2' })

Is there a simple way to disable this behaviour?

2 Answers

Just in case anyone else stumbles upon this, it looks like mongoose will be supporting this according to this issue.

you can use lean() method with your find/findOne queries. lean() will remove all the effect a mongoose schema has, i.e. it will return data as it is saved in MongoDB without any typecasting.

Note:- After using lean() you will not be able to call update or save on that returned data. Also, this will increase your query performance.

example

Model.find().lean().exec((err, result) => {
    console.log(result);    //data without any typecasting
    /*some operations on result*/
    result.save(); // this will not work  
});
Related