猫鼬 - 从其他领域获得_id

  • 本文关键字:id 其他 猫鼬 mongoose
  • 更新时间 :
  • 英文 :


我有一个模型Person.模型Person具有字段firstNamesecondName

现在,为了填充,我希望每个Person_id字段始终等于firstName + " " + secondName

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

自定义二传手就是答案。

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