Home > Mobile >  SMS are not saving in database
SMS are not saving in database

Time:11-22

Nodejs, MongoDB, Rest API I'm using here twilio services for sending the phone otp SMS in MongoDB database, SMS are sending and no errors but otps are not saving in the database. Please help me how to save the otps in the database.

try {
        const { phone } = req.body;
        const user = await User.findOne({ phone: phone });

        if (!user) {
            return res.status(404).json({ success: false, message: 'Phone not found.' 
            })
        }

        const accountSid = process.env.TWILIO_ACCOUNT_SID;
        const authToken = process.env.TWILIO_AUTH_TOKEN;
        const client = require('twilio')(accountSid, authToken);

        client.verify.services.create({friendlyName: `My First Verify Service` })
            .then(service => console.log(service.sid));

        client.verify.services(process.env.TWILIO_SERVICES_KEY)
            .verifications
            .create({ to: user.phone, channel: `sms ` })
            .then(verification => {
            console.log(verification.status)
        });

        client.verify.services(process.env.TWILIO_SERVICES_KEY)
           .verificationChecks
           .create({to: user.phone, code: `${user.phoneOtp}`})
           .then(verification_check => console.log(verification_check.status));



        await user.save();


        return res.status(200).json({ success: true, message: 'OTP sended to your 
             registered phone number.' });
        } catch (err) {
            return res.status(200).json({ success: false, message: 'OTP not send try 
             again' });
        }

CodePudding user response:

Try putting await user.save(); inside your service through which you are sending the sms. You can put it inside .then.

CodePudding user response:

From what I see here, you are not saving the OTP to the database yet. Right after sending the OTP add user.phoneOtp = code; and await user.save(); before proceeding.

  • Related