Kiran Bhattarai
Kiran Bhattarai

Reputation: 175

Pass the results of the query to the outside variable

I am new to node.js and i am trying to create the reset password module for my app. I got stuck on a problem where I wanted to access the result outside of a query.

router.post('/forgot',(req,res)=>{
  const db = require('../db.js');
  if (req.body.email !== undefined) {
    var emailAddress = req.body.email;
    // TODO: Using email, find user from your database.
    db.query('SELECT * FROM users WHERE email = ?',[emailAddress],(err,results,fields)=>{
      if(err){
        console.log('Error in pulling the information of the user from the database');
      }

      var  userid = results[0].id;
      console.log(userid);
    });
    var payload = {
        id: userid,        // User ID from database
        email: emailAddress
    };
    console.log(payload);
} else {
    res.send('Email address is missing.');
}
});

I want to get the value of userid which i got from my database and pass it to my outside variable payload and store it in the

id: userid

I did my research on other similar question but was not clear on this topic so any help will be highly appreciated. Thankyou

Upvotes: 0

Views: 188

Answers (1)

jsasuga
jsasuga

Reputation: 68

You're using a callback function here to get the result of your query, what this means is after the query is run it will go ahead and go through the function in the parameter the (err, results, fields) => { ... }, so you could either build your payload inside that callback function, where you would already have the userid on results[0].id or call another function inside that callback with the userid as a parameter.

Something like this

router.post('/forgot', (req, res) => {
    const db = require('../db.js');
    if (req.body.email !== undefined) {
        var emailAddress = req.body.email;
        // TODO: Using email, find user from your database.
        db.query('SELECT * FROM users WHERE email = ?', [emailAddress], (err, results, fields) => {
            if (err) {
                console.log('Error in pulling the information of the user from the database');
            }

            var userid = results[0].id;
            console.log(userid);


            buildPayload(userid, emailAddress)
        });
    } else {
        res.send('Email address is missing.');
    }
});

buildPayload(userId, emailAddress) {
    var payload = {
        id: userId,        // User ID from database
        email: emailAddress
    };
    console.log(payload);


    // whatever else you need to do
}

Upvotes: 1

Related Questions