【问题标题】:Mongoose setting strict to false disables validationMongoose 将严格设置为 false 禁用验证
【发布时间】: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 的要点。我不知道这存在。

标签: node.js mongodb mongoose


【解决方案1】:

经过一番尝试,我想出了一个可行的解决方案。如果以后有 Mongoose 用户遇到同样的问题,我会在这里发布。

诀窍是在 Mongoose 文档上使用 save 方法。出于某种原因,这确实可以正确运行验证器,同时还允许使用 strict 选项。

所以更新文档的基本过程如下所示:

  • 使用Model.findOne查找文档
  • 将更新应用到文档(例如通过合并现有文档中的更新值)
  • 在文档上致电save

在代码中:

    // Find the document you want to update
    Model.findOne({name: "Me"}, function(error, document) {
        if(document) {
            // Merge the document with the updates values
            merge(document, newValues);

            document.save(function(saveError) {
                // Whatever you want to do after the update
            });
        }
        else {
            // Mongoose error or document not found....
        }
    });

    // Merges to objects and writes the result to the destination object.
    function merge(destination, source) {
        for(var key in source) {
            var to = destination[key];
            var from = source[key];

            if(typeof(to) == "object" && typeof(from) == "object")
                deepMerge(to, from);
            else if(destination[key] == undefined && destination.set)
                destination.set(key, from);
            else
                destination[key] = from;
        }
    }

【讨论】:

    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多