I am currently working on a user registration setup. In the user model, I have defined apiKey as a property of the user and I want to set it equal to the user object Id. How can I do this ? Here is my code for the model :
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
}
);
CodePudding user response:
You can use mongoose hooks here. First you need to update your apiKey to apiKey: {type:Schema.Types.ObjectId required: false },
and then add the below code to your model file
userScheama.pre('save', async function (next) {
this.apiKey = this._id;
next();
});