问题
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