我有一个mongoose架构,我想使用属性的值作为另一个属性的默认值,如:
schemaDef = {
myProperty: {type: String, required: true}
...
otherProperty: {type: String, default: this.myProperty}
}
我认为这是可能的,但显然不是,有人可以确认并可能给我一个参考吗?
答案 0 :(得分:1)
虽然没有内置方法,但您可以编写一些辅助函数来表现它们,就像您想要的那样。示例模式:
module.exports = function(){
var schemaDef = {
email : {type : String, required: true},
secondaryEmail : {type : String, required: true, selfDefault: "email"},
fullName : {type : String, required: true, selfDefault: {fields: ["firstName","middleName", "lastName"], space: true}},
password: {type: String, required: true},
firstName : {type : String, required: true},
middleName : {type : String, required: true},
lastName : {type : String, required: true}
};
var selfDefaults = initSelfDefaults(schemaDef);
var UserSchema = new Schema(schemaDef);
UserSchema.pre('validate', function(next) {
setSelfDefaults(this, selfDefaults)
next();
});
return mongoose.model("User", UserSchema);
};
您可以将以下帮助函数放在其他文件中以要求并将它们用于所有模型/模式:
// gets and returns all selfDefaults from the scehmaDef obj. Throws error if selfDefault reference is invalid
function initSelfDefaults(schemaDef){
var defaults = {};
for(var key in schemaDef){
if(schemaDef[key].selfDefault){
if(schemaDef[key].selfDefault.fields){
schemaDef[key].selfDefault.fields.forEach(function(field){
if (!schemaDef[field]){
throw new Error(field + " is an invalid selfDefault reference")
}
})
}
else if(!schemaDef[schemaDef[key].selfDefault]){
throw new Error(schemaDef[key].selfDefault + " is an invalid selfDefault reference")
}
defaults[key] = schemaDef[key].selfDefault;
delete schemaDef[key].selfDefault;
}
};
return defaults
}
// sets the selfDefaults for the fields of the document being created if the fields are empty
function setSelfDefaults(doc, defaults){
for(var key in defaults){
if(!doc[key]){
if(defaults[key].fields){
var fields = [];
for(var i=0; i<defaults[key].fields.length; i++){
if(doc[defaults[key].fields[i]]){
fields.push(doc[defaults[key].fields[i]])
}
}
doc[key] = defaults[key].space? fields.join(" ") : fields.join("");
}
else{
doc[key] = doc[defaults[key]];
}
}
}
return;
}
它不适用于嵌套模式,但你可以调整代码来实现它。