如何在猫鼬中获取用户的objectId
How to get objectId of user in mongoose
我目前正在处理用户注册设置。在用户模型中,我已将 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
}
);
您可以在此处使用 mongoose 挂钩。首先,您需要将 apiKey 更新为 apiKey: {type:Schema.Types.ObjectId required: false },
,然后将以下代码添加到您的模型文件中
userScheama.pre('save', async function (next) {
this.apiKey = this._id;
next();
});
我目前正在处理用户注册设置。在用户模型中,我已将 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
}
);
您可以在此处使用 mongoose 挂钩。首先,您需要将 apiKey 更新为 apiKey: {type:Schema.Types.ObjectId required: false },
,然后将以下代码添加到您的模型文件中
userScheama.pre('save', async function (next) {
this.apiKey = this._id;
next();
});