Home > other >  Is it possible to use one specific mysql result as an object ? NodeJS
Is it possible to use one specific mysql result as an object ? NodeJS

Time:06-09

I got my MySQL data printed in console.log() as console.log(result) and it works fine.

Now I need to use this result to define variable MyPlan in a different function.

This is how I got the results from MySQL db:

function load() {
    
    var MySQL = SQL.createConnection(credentials)
    MySQL.connect((err) => {
          if(err) {
             console.log(err);
             process.exit(0);
          }
        
          for(var i = 0; i < 250; i  ) console.log('\n');
         console.log('Successfuly logged in!');
          
    });
           MySQL.query("SELECT plan FROM users WHERE username = 'asd123'", (err, rows) => {
               
               if(err) { console.log(`[!] SQL Error: ${err}`); return; }
              
             rows.forEach((results) => {
                    console.log(results); //output: RowDataPacket { plan: 300 }
               });
               
           });
               
}
load();

I need MyPlan: to be declared with a number 300 as stated above.

    startMyPlan() {

        //var theoric = 10;
        this.botCountInt = setInterval(() => {
            let json = {
                connected: 0,
                MyPlan:   //300

            };
            this.send(json);
        }, 100); 
    }

I tried to define results in first function like this:

             rows.forEach((results) => {
            myresult = results //first option
        // OR LIKE THIS:
            this.myresult = results; //second option
                    console.log(results); 
               });

and write it in startMyPlan() as

            let json = {
                connected: 0,
                MyPlan: this.myresult

            };

But first option gave me error myresult is not defined and second option gave me different error: Cannot set properties of undefined(setting 'myresult').

EDIT: I guess my problem is that results won't give me correct output OUTSIDE that function where it's created. It returns undentified when I try to run console.log(results); once it's run outside load() function

CodePudding user response:

So, as per my understanding, you have not defined the myresult variable in any scope. The first option will work if you do var myresult=undefined just before rows.forEach((results) => call. One example:

var rows = [{ "test": "foo1" }, { "test": "foo2" }, { "test": "foo3" }, { "test": "foo4" }];
var myresult;
rows.forEach((results) => {
    myresult = results //first option
    console.log(myresult);
});

console.log(myresult);

I am not sure what exactly you want to do with myresult. But I think above example will be enough to understand things.

  • Related