Lorenzo
Lorenzo

Reputation: 225

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.

Upvotes: 8

Views: 5833

Answers (2)

Sameer Ingavale
Sameer Ingavale

Reputation: 2210

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

Upvotes: 6

gnerkus
gnerkus

Reputation: 12019

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();
});

Upvotes: 9

Related Questions