這是我的架構...
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();
...我希望我的 person 物件具有第三個名為“fullName”的虛擬欄位,如下所示:
console.warn('result');
// result = {
// firstName: 'Rick',
// lastName: 'Biruel',
// fullName: 'Rick Biruel'
// };
為了達到這個結果,我嘗試了這個無濟于事......
personSchema.post('save', async function () {
this.fullName = `${this.firstName} ${this.lastName}`;
});
PS 沒有發生錯誤,但我的人員物件中不存在第三個欄位“fullName”。該fullName欄位不得保留在資料庫中!
uj5u.com熱心網友回復:
您可以使用VirtualType來實作這一點,您還可以在 Mongoose 官方檔案中找到與您的問題非常相似的示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438872.html
