How to access a RowDataPacket object

前端 未结 14 2339
悲&欢浪女
悲&欢浪女 2020-11-29 03:02

I\'m currently developing a desktop application with Node-webkit. During that process I need to get some data from a local MySQL-database.

The querying works fine, b

相关标签:
14条回答
  • I really don't see what is the big deal with this I mean look if a run my sp which is CALL ps_get_roles();. Yes I get back an ugly ass response from DB and stuff. Which is this one:

    
    [
      [
        RowDataPacket {
          id: 1,
          role: 'Admin',
          created_at: '2019-12-19 16:03:46'
        },
        RowDataPacket {
          id: 2,
          role: 'Recruiter',
          created_at: '2019-12-19 16:03:46'
        },
        RowDataPacket {
          id: 3,
          role: 'Regular',
          created_at: '2019-12-19 16:03:46'
        }
      ],
      OkPacket {
        fieldCount: 0,
        affectedRows: 0,
        insertId: 0,
        serverStatus: 35,
        warningCount: 0,
        message: '',
        protocol41: true,
        changedRows: 0
      }
    ]
    
    

    it is an array that kind of look like this:

    
    rows[0] = [
        RowDataPacket {/* them table rows*/ },
        RowDataPacket { },
        RowDataPacket { }
    ];
    
    rows[1] = OkPacket {
       /* them props */
    }
    
    

    but if I do an http response to index [0] of rows at the client I get:

    [
      {"id":1,"role":"Admin","created_at":"2019-12-19 16:03:46"}, 
      {"id":2,"role":"Recruiter","created_at":"2019-12-19 16:03:46"},
      {"id":3,"role":"Regular","created_at":"2019-12-19 16:03:46"}
    ]
    

    and I didnt have to do none of yow things

    rows[0].map(row => {
       return console.log("row: ", {...row});
    });
    

    the output gets some like this:

    row:  { id: 1, role: 'Admin', created_at: '2019-12-19 16:03:46' }
    row:  { id: 2, role: 'Recruiter', created_at: '2019-12-19 16:03:46' }
    row:  { id: 3, role: 'Regular', created_at: '2019-12-19 16:03:46' }
    

    So you all is tripping for no reason. Or it also could be the fact that I'm running store procedures instead of regular querys, the response from query and sp is not the same.

    0 讨论(0)
  • 2020-11-29 03:03

    going off of jan's answer of shallow-copying the object, another clean implementation using map function,

    High level of what this solution does: iterate through all the rows and copy the rows as valid js objects.

    // function  will be used on every row returned by the query
    const objectifyRawPacket = row => ({...row});
    
    // iterate over all items and convert the raw packet row -> js object
    const convertedResponse = results.map(objectifyRawPacket);
    

    We leveraged the array map function: it will go over every item in the array, use the item as input to the function, and insert the output of the function into the array you're assigning.

    more specifically on the objectifyRawPacket function: each time it's called its seeing the "{ RawDataPacket }" from the source array. These objects act a lot like normal objects - the "..." (spread) operator copies items from the array after the periods - essentially copying the items into the object it's being called in.

    The parens around the spread operator on the function are necessary to implicitly return an object from an arrow function.

    0 讨论(0)
  • 2020-11-29 03:04
    db.query('select * from login',(err, results, fields)=>{
        if(err){
            console.log('error in fetching data')
        }
        var string=JSON.stringify(results);
        console.log(string);
        var json =  JSON.parse(string);
       // to get one value here is the option
        console.log(json[0].name);
    })
    
    0 讨论(0)
  • 2020-11-29 03:06

    Simpler way:

    .then( resp=> {
      let resultFromDb= Object.values(resp)[0]
      console.log(resultFromDb)
    }
    

    In my example I received an object in response. When I use Object.values I have the value of the property as a response, however it comes inside an array, using [0] access the first index of this array, now i have the value to use it where I need it.

    0 讨论(0)
  • 2020-11-29 03:07

    If anybody needs to retrive specific RowDataPacket object from multiple queries, here it is.

    Before you start

    Important: Ensure you enable multipleStatements in your mysql connection like so:

    // Connection to MySQL
    var db = mysql.createConnection({
      host:     'localhost',
      user:     'root',
      password: '123',
      database: 'TEST',
      multipleStatements: true
    });
    

    Multiple Queries

    Let's say we have multiple queries running:

      // All Queries are here
      const lastCheckedQuery = `
        -- Query 1
        SELECT * FROM table1
        ;
    
        -- Query 2
        SELECT * FROM table2;
        `
        ;
    
      // Run the query
      db.query(lastCheckedQuery, (error, result) => {
        if(error) {
          // Show error
          return res.status(500).send("Unexpected database error");
        }
    

    If we console.log(result) you'll get such output:

    [
      [
        RowDataPacket {
          id: 1,
          ColumnFromTable1: 'a',
        }
      ],
      [
        RowDataPacket {
          id: 1,
          ColumnFromTable2: 'b',
        }
      ]
    ]
    

    Both results show for both tables.

    Here is where basic Javascript array's come in place https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

    To get data from table1 and column named ColumnFromTable1 we do

    result[0][0].ColumnFromTable1 // Notice the double [0]
    

    which gives us result of a.

    0 讨论(0)
  • 2020-11-29 03:09

    With Object.prototype approach, JSON.parse(JSON.stringify(rows)) returns object, extract values with Object.values()

    var resultArray = Object.values(JSON.parse(JSON.stringify(rows)))
    

    Usage:

    resultArray.forEach(function(v){ console.log(v) })
    
    0 讨论(0)
提交回复
热议问题