this is my schema
i want to automatically expire this field after 5 minutes. how i do that?
const userRegistrationSchema = new mongoose.Schema({
mobile: {
type: Number, trim: true,
},
email: {
type: String, lowercase: true, trim: true
},
// email Varification
verified: {
type: Boolean,
},
otp: {
type: Number,
},
password: {
type: String, trim: true,
},
confirmPassword: {
type: String, trim: true,
},
if user enter this value and otp store like this
mobile: 9561300851
email: "[email protected]"
verified: false
otp: 8236
and after 5 minutes i want to my data look like with otp field
mobile: 9561300851
email: "[email protected]"
verified: false
I hope I have explained my problem then how to do it.
2
Answers
AFAIK MongoDB only supports TTL on documents, not on fields: https://www.mongodb.com/docs/manual/core/index-ttl/
You could consider creating a separate OTP schema that has a TTL index of 5 minutes. The relevant Mongoose documentation can be found here:
https://mongoosejs.com/docs/api.html#schemadateoptions_SchemaDateOptions-expires
MongoDB supports documents deletion only after a certain time using TTL. However for field deletion what you can do is after using the OTP you can remove the field using $unset.
https://www.mongodb.com/docs/manual/reference/operator/update/unset/
Or, you can create scheduler which will run after certain time and remove all the used OTP field using $unset.