使用猫鼬保存后附加一个新的虚拟字段

Attach a new virtual field after save using mongoose

这是我的架构...

const personSchema = new Schema({
  firstName: String,
  lastName: String
});

这是我的模型...

const PersonModel = model('Persons', personSchema, 'persons');

这是我的人物对象

const person = new PersonModel({
  firstName: 'Rick',
  lastName: 'Biruel'
});

当我保存对象时...

const result = await person.save();

...我希望我的人反对第三个名为 'fullName' 的虚拟字段,如下所示:

console.warn('result');
// result = {
//   firstName: 'Rick',
//   lastName: 'Biruel',
//   fullName: 'Rick Biruel'
// };

为了达到这个效果,我试了这个也没用....

personSchema.post('save', async function () {
  this.fullName = `${this.firstName} ${this.lastName}`;
});

P.S。没有错误发生,但第三个字段 'fullName' 在我的 person 对象中不存在。 fullName 字段不得保留在数据库中!

您可以使用 VirtualType, and you can also find an example 实现此目的,这与您在 Mongoose 官方文档中遇到的问题非常相似。