admin管理员组文章数量:1244258
I have this mongoose schema:
var UserSchema = new Schema({
"name":String,
"gender":String,
});
I want to add another field named image. This image will have a default value if gender is male
and it will have another default value if gender is female
. I found that the default value can be set with:
image: { type: ObjectId, default: "" }
But I do not find how can I set it with condition.
I have this mongoose schema:
var UserSchema = new Schema({
"name":String,
"gender":String,
});
I want to add another field named image. This image will have a default value if gender is male
and it will have another default value if gender is female
. I found that the default value can be set with:
image: { type: ObjectId, default: "" }
But I do not find how can I set it with condition.
Share Improve this question edited Mar 30, 2016 at 21:48 gnerkus 12k7 gold badges53 silver badges74 bronze badges asked Mar 30, 2016 at 21:10 LorenzoLorenzo 2254 silver badges10 bronze badges2 Answers
Reset to default 9You can achieve this with the use of a document middleware.
The pre:save
hook can be used to set a value on the document before it is saved:
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();
});
You can set the 'default' option to a function that tests for some condition. The return value of the function is then set as the default value when the object is first created. This is how it would look like.
image: {
type: ObjectId,
default: function() {
if (this.gender === "male") {
return male placeholder image;
} else {
return female placeholder image;
}
}
}
For the specific purpose of setting up a default placeholder image, I think using a link as the default value is a much simpler approach. This is how the schema would look like.
image: {
type: String,
default: function() {
if (this.gender === "male") {
return "male placeholder link";
} else {
return "female placeholder link";
}
}
}
These are links to the placeholder images if someone might need them.
https://i.ibb.co/gSbgf9K/male-placeholder.jpg
https://i.ibb.co/dKx0vDS/woman-placeholder.jpg
本文标签:
版权声明:本文标题:javascript - How to set the value of a default attribute of a Mongoose schema based on a condition - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740114790a2226874.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论