我目前正在處理用戶注冊設定。在用戶模型中,我已將 apiKey 定義為用戶的屬性,并且我想將其設定為等于用戶物件 ID。我怎樣才能做到這一點 ?這是我的模型代碼:
const userScheama = new mongoose.Schema(
{
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
name: {
type: String,
trim: true,
required: true
},
hashed_password: {
type: String,
required: true
},
apiKey:{
type: String,
required: false,
},
plan:{
type: String,
required: false
},
salt: String,
role: {
type: String,
default: 'subscriber'
},
resetPasswordLink: {
data: String,
default: ''
}
},
{
timestamps: true
}
);
uj5u.com熱心網友回復:
你可以在這里使用貓鼬鉤子。首先,您需要將您的 apiKey 更新為apiKey: {type:Schema.Types.ObjectId required: false },,然后將以下代碼添加到您的模型檔案中
userScheama.pre('save', async function (next) {
this.apiKey = this._id;
next();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/440648.html
上一篇:節點專案與實踐
