我有一个模型false
。模型Person
具有字段Person
和firstName
。
现在,出于填充的目的,我希望每个secondName
的{{1}}字段始终等于_id
。
实现此目标的正确方法是什么?
答案 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 } }
);