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.
You 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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With