最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set the value of a default attribute of a Mongoose schema based on a condition - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 9

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

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论