我有这个猫鼬模式:
var UserSchema = new Schema({
"name":String,
"gender":String,
});
我想添加另一个名为image的字段。如果性别为male
,则此图片将具有默认值,如果性别为female
,则该图片将具有其他默认值。我发现默认值可以设置为:
image: { type: ObjectId, default: "" }
但是我找不到如何设置条件。
答案 0 :(得分:4)
您可以使用document middleware。
来实现这一目标 pre:save
挂钩可用于在保存文档之前设置值:
var UserSchema = new Schema({
"name":String,
"gender":String,
});
UserSchema.pre('save', function(next) {
if (this.gender === 'male') {
this.image = 'Some value';
} else {
this.image = 'Other value';
}
next();
});
答案 1 :(得分:1)
您可以将“默认”选项设置为测试某些条件的功能。然后,在首次创建对象时,将函数的返回值设置为默认值。看起来就是这样。
image: {
type: ObjectId,
default: function() {
if (this.gender === "male") {
return male placeholder image;
} else {
return female placeholder image;
}
}
}
对于设置默认占位符图像的特定目的,我认为使用链接作为默认值是一种更简单的方法。这就是架构的样子。
image: {
type: String,
default: function() {
if (this.gender === "male") {
return "male placeholder link";
} else {
return "female placeholder link";
}
}
}
如果有人需要的话,这些是到占位符图像的链接。