是否可以禁用Mongoose SchemaTypes的自动类型转换?

时间:2017-11-23 22:51:17

标签: node.js validation mongoose schema

对于具有此Schema的模型...

{ name: { type: String } }

...以下内容会自动将提供的值转换为字符串,而不是强制执行类型:

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

是否有一种简单的方法可以禁用此行为?

3 个答案:

答案 0 :(得分:0)

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

你可以试试像:

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

  return v;
},

答案 1 :(得分:0)

您可以在您的find / findOne查询中使用lean()方法。 lean()将删除猫鼬模式的所有作用,即它将返回数据,因为它保存在MongoDB中而不进行任何类型转换。

注意:-:使用lean()后,您将无法调用更新或保存返回的数据。 另外,这将提高您的查询性能。

示例

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

答案 2 :(得分:0)

以防万一其他人偶然发现了这个问题,根据this issue,似乎猫鼬会支持这一点。

相关问题