猫鼬-从其他字段派生_id

时间:2020-05-27 11:19:25

标签: mongoose

我有一个模型false。模型Person具有字段PersonfirstName

现在,出于填充的目的,我希望每个secondName的{​​{1}}字段始终等于_id

实现此目标的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

自定义设置器就是答案。

const personSchema = new mongoose.Schema(
  {
    _id: String,
    name: {
      first: {
        type: String,
        required: true,
        index: true,
        set: function (this: IPerson, v: string) {
          this.name.first = v;
          this._id =
            (this.name.last ? " " + this.name.last : "") +
            (this.name.middle ? " " + this.name.middle : "") +
            (this.name.first ? " " + this.name.first : "");
          return v;
        },
      },
      middle: {
        type: String,
        index: true,
        set: function (this: IPerson, v: string) {
          this.name.middle = v;
          this._id =
            (this.name.last ? " " + this.name.last : "") +
            (this.name.middle ? " " + this.name.middle : "") +
            (this.name.first ? " " + this.name.first : "");
          return v;
        },
      },
      last: {
        type: String,
        required: true,
        index: true,
        set: function (this: IPerson, v: string) {
          this.name.last = v;
          this._id =
            (this.name.last ? " " + this.name.last : "") +
            (this.name.middle ? " " + this.name.middle : "") +
            (this.name.first ? " " + this.name.first : "");
          return v;
        },
      },
      full: {
        type: String,
        index: true,
        set: () => {
          throw new Error("person.name.full is readonly.");
        },
      },
    },
    isEntity: {
      type: Boolean,
      required: true,
    },
  },
  { toObject: { virtuals: true } }
);