【发布时间】:2016-03-23 20:16:42
【问题描述】:
我有以下架构
var Schema = new mongoose.Schema({
type: {required: true, type: String, enum: ["device", "beacon"], index: true},
device: {
type: {type: String},
version: {type: String},
model: {type: String}
},
name: String,
beaconId: {required: false, type: mongoose.Schema.Types.ObjectId},
lastMeasuredTimestamp: {type: Number, index: true},
lastMeasuredPosition: {type: [Number], index: "2dsphere"},
lastMeasuredFloor: {type: Number, index: true}
}, {strict: false});
请注意,我已将 strict 设置为 false。这是因为将架构中未定义的自定义属性添加到文档中是有效的。
接下来我执行以下查询
DB.Document.update({_id: "SOME_ID_HERE"}, {$set: {type: "bull"}}, {runValidators: true})
这会将属性“类型”更改为根据 Mongoose 架构无效的值。我使用 runValidators 选项来确保运行模式验证。
然而,此查询的最终结果是“type”更改为“bull”并且不运行验证。当我将 strict 设置为 true 时,验证确实会运行并且(正确)显示错误。
为什么严格会影响验证是否运行?当我查看此描述 http://mongoosejs.com/docs/guide.html#strict 时,它只提到严格限制添加未在架构中定义的属性(我不希望此特定架构出现这种情况)。
安装信息:
- Ubuntu 14.04 LTS
- MongoDB 3.0.8
- 猫鼬 4.2.3
- NodeJS 0.10.25
- NPM 1.3.10
【问题讨论】:
-
我认为这个问题与猫鼬GitHub存储库中的this issue有关。
-
可能不是您正在寻找的答案,但您可以通过使用 {strict: true}、{runValidators: true} 并在您的包含所有自定义字段的 {data: {type: Schema.Types.Mixed}} 架构。
-
@leroydev 我认为您可能是对的,感谢您的链接!
-
@DerekSoike 关于 Schema.Types.Mixed 的要点。我不知道这存在。