Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the value of a default attribute of a Mongoose schema based on a 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.

like image 779
Lorenzo Avatar asked Mar 30 '16 21:03

Lorenzo


1 Answers

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();
});
like image 87
gnerkus Avatar answered Sep 30 '22 13:09

gnerkus