【问题标题】:Mongoose Schema validate XOR fieldsMongoose Schema 验证 XOR 字段
【发布时间】:2015-05-19 19:44:17
【问题描述】:

我有以下猫鼬模式

var Mongoose = require("mongoose");
var Schema = Mongoose.Schema;

var headerSchema = new Schema({
    lang : {
        type: String,
        required: true,
        match: [ /^(en|es|pt)$/, "{VALUE} is not a supported language" ],
        index: { unique: true }
    },
    menu : {
        type: [{
            link: { type: Schema.ObjectId, ref: "Link"},
            dropdown: { type: Schema.ObjectId, ref: "Dropdown"},
            autopopulate: true
        }]
    }
});

headerSchema.plugin(require("mongoose-autopopulate"));

module.exports = Mongoose.model("header", headerSchema);

您可能已经猜到了,这描述了网页标题的配置文档。此标头有一个导航(架构中的菜单),其中每个项目可以是下拉列表或链接,但不能同时是两者。有没有办法将自定义验证添加到我的架构中,以仅在设置了其中任何一个时才允许保存文档,但不能同时设置,也不能两者都设置? (想想布尔运算 XOR)

例如,这是一个有效的头文件:

{
  lang: "es",
  menu: [{
    link: {
      title: "Contact",
      href: "/contact"
    }
  }, {
    dropdown: {
     title: "FAQ",
     links: [{
       title: "What is this?",
       href : "/about"
     }]
    }
  }]
}

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这似乎有效:

    menu : {
        type: [{
            type: Schema.Types.Mixed,
            required: true,
            validate: [ isDropdownOrLink, "{VALUE} is neither a dropdown nor a link" ]
        }]
    }
    
    function isDropdownOrLink (value) {
        if (!value) {
            return false;
        }
    
        return value instanceof Link || value instanceof Dropdown;
    }
    

    还使用 Schema.Types.Mixed 简化了我的架构。不过,我现在将问题留待解决,因为我的回答稍微改变了原始问题(因为我已经更改了架构)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多