目前我有兩個幾乎相同的模式:貓鼬:擴展模式
var userSchema = mongoose.Schema({
email: {type: String, unique: true, required: true, validate: emailValidator},
passwordHash: {type: String, required: true},
firstname: {type: String, validate: firstnameValidator},
lastname: {type: String, validate: lastnameValidator},
phone: {type: String, validate: phoneValidator},
});
而且
var adminSchema = mongoose.Schema({
email: {type: String, unique: true, required: true, validate: emailValidator},
passwordHash: {type: String, required: true},
firstname: {type: String, validate: firstnameValidator, required: true},
lastname: {type: String, validate: lastnameValidator, required: true},
phone: {type: String, validate: phoneValidator, required: true},
});
他們唯一的區別是在驗證:用戶不需要名字,姓氏或電話。但管理員必須定義這些屬性。
不幸的是,上面的代碼不是非常乾燥,因爲它們幾乎完全相同。因此,我想知道是否有可能建立一個基於userSchema
的adminSchema
。例如:
var adminSchema = mongoose.Schema(userSchema);
adminSchema.change('firstname', {required: true});
adminSchema.change('lastname', {required: true});
adminSchema.change('phone', {required: true});
顯然這只是僞代碼。是這樣的可能嗎?
另一個非常類似的問題是,如果可以基於另一個創建新的模式,併爲其添加更多的屬性。例如:
var adminSchema = mongoose.Schema(userSchema);
adminSchema.add(adminPower: Number);
而且人們還是這麼做https://github.com/briankircho/mongoose-schema-extend看到這個。 – diproart