繁体   English   中英

如何根据条件设置 Mongoose 模式的默认属性值

[英]How to set the value of a default attribute of a Mongoose schema based on a condition

我有这个猫鼬模式:

var UserSchema = new Schema({
    "name":String, 
    "gender":String,
});

我想添加另一个名为 image 的字段。 此图片将有一个默认值,如果性别是male ,这将有另一个默认值,如果性别为female 我发现默认值可以设置为:

image: { type: ObjectId, default: "" }

但我不知道如何设置条件。

您可以使用文档中间件来实现这一点。

pre:save钩子可用于在保存文档之前在文档上设置一个值:

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

您可以将 'default' 选项设置为测试某些条件的函数。 函数的返回值然后被设置为第一次创建对象时的默认值。 这就是它的样子。

image: {
    type: ObjectId,
    default: function() {  
       if (this.gender === "male") {
          return male placeholder image;
       } else {
        return female placeholder image;
      } 
    }
}

对于设置默认占位符图像的特定目的,我认为使用链接作为默认值是一种更简单的方法。 这就是架构的样子。

image: {
    type: String,
    default: function() {
       if (this.gender === "male") {
          return "male placeholder link";
       } else {
          return "female placeholder link";
       }
    }
 }

如果有人可能需要它们,这些是占位符图像的链接。

https://i.ibb.co/gSbgf9K/male-placeholder.jpg

https://i.ibb.co/dKx0vDS/woman-placeholder.jpg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM