2015-05-19 141 views
0

我有貓鼬架構貓鼬模式驗證XOR領域

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); 

正如你可能已經猜到下面,這說明了一個網頁的頭一個配置文件。這個頭部有一個導航(模式中的菜單),其中每個項目可以是一個下拉菜單或一個鏈接,但不是兩個。有沒有辦法將自定義驗證添加到我的模式,只允許保存文檔,如果其中任何一個設置,但不是兩者都不是? (想想布爾運算異或)

例如,這是一個有效的頭文件:

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

回答

0

這似乎工作:

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簡化我的架構。儘管如此,我仍然留下了這個問題,因爲我的答案有點改變了原來的問題(因爲我已經改變了模式)