I have some backend code written in Nodejs that identifies the user and sends an OTP to their email.
Before I send the OTP via mail, I want to store it in my MongoDB database, so that I can later validate the user using the OTP.
Here’s the NodeJS code:
//generates a cryptographically secure 6 digit long code:
const otp = otpgen_function()
//Store the OTP in DB:
const newToken = await new Token({user_id: user_record._id,token: otp})
const saveToken = await newToken.save()
Here’s the schema of Token:
const mongoose = require('mongoose')
const ObjectId = mongoose.Schema.ObjectId
const TokenSchema = mongoose.Schema({
user_id:{
type: ObjectId,
required: true,
ref: 'mis'
},
token:{
type: String,
required: true,
},
createdAt:{
type: Date,
default: Date.now(),
index: {expires:'15m'}
}
})
module.exports = mongoose.model('Token',TokenSchema)
The createdAt field ensures that the OTP is deleted from the DB after 15 mins.
However, for some reason Mongoose doesn’t save the OTP record when I call save()
In fact the behavior of save is very… erratic:
-
Sometimes it saves the OTP record and it stays there,
-
other times it is saved and can be seen in the collection, but
disappears after a few seconds. -
However most of the time, it just doesn’t save the record…
Any ideas as to what may be going wrong?
2
Answers
So it turns out that the index I specified in the schema:
Was the source of the problem. Earlier for testing I had kept the expiry to a few seconds. Later, I changed the value to 15 minutes. However, mongoose didn't update the index in MongoDB, so I had to manually do it by executing the following in my MongoShell:
And then restarted my NodeJS server. Doing these things solved the issue
Sometimes it may be complicated when trying to create a model with its constructor and save it. Have you tried
Token.create()
method ?