简体   繁体   中英

Calling save() on the object of a model in Mongoose doesn't save the record to MongoDB

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?

Sometimes it may be complicated when trying to create a model with its constructor and save it. Have you tried Token.create() method ?

So it turns out that the index I specified in the schema:

index: {expires:'15m'}

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:

db.tokens.dropIndex('createdAt_1')

And then restarted my NodeJS server. Doing these things solved the issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM