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

混江龙づ霸主 提交于 2020-01-24 11:38:08

问题


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?


回答1:


What about Here

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

var Number = mongoose.model('Number', numberSchema);

var doc = new Number();
doc.integerOnly = 2.001;
doc.integerOnly; // 2
doc.i; // 2
doc.i = 3.001;
doc.integerOnly; // 3
doc.i; // 3

Can you try something like :

set: (v) => {
  if (typeof v !== 'string') throw new Error('zdokd');

  return v;
},



回答2:


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  
});



回答3:


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



来源:https://stackoverflow.com/questions/47464220/is-it-possible-to-disable-automatic-type-casting-for-mongoose-schematypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!