我有以下架构:
const playerSchema = mongoose.Schema({
firstName: {
type: String,
required: true,
trim: true,
maxlength: 50,
lowercase: true
},
lastName: {
type: String,
required: true,
trim: true,
maxlength: 50,
lowercase: true
},
displayName: {
type: String,
set: getDisplayName
},
photoUrl: String,
playerType: String,
teams: [
{
type: mongoose.Schema.ObjectId,
ref: 'Team'
}
]
})
现在,我要设置displayName,使firstName的首字母大写,然后跟空格和lastname。现在,我为此使用以下功能:
const getDisplayName = function() {
let firstName = this.firstName
const extractedFirstName = firstName.substring(0, 1);
return `${extractedFirstName.toUpperCase()} ${this.lastName}`
}
现在我的问题是可以使用this.firstName它将成功运行吗?当firstName和lastName尚未设置和保存时,在设置displayName时会出现问题。我想要一些专家建议。