Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse the data from "rows" object in node.js,express.js,mysql2

I m using the node,express,mysql2 packages .When i m using console.log(rows) ,it is giving me following output:

[{"userid": "test","password": "test"}]

And here is my Code :

var application_root = __dirname,
express = require("express"),
mysql = require('mysql2');
path = require("path");
var app = express();

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123',
database: "bbsbec"
 });
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

connection.query('SELECT * from pass', function(err, rows) {
     res.json(rows);
     console.log(rows);
   });

I just want to know that how can i parse this "rows" object so that i can retrive both userid and password .

like image 374
jaassi Avatar asked Mar 13 '14 14:03

jaassi


People also ask

What is Express () in node JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.

Does express js have ORM?

How Prisma and Express fit together. Prisma is a next-generation ORM that's used to query your database in an Express server. You can use it as an alternative to writing plain SQL queries, to using query builders like knex. js or to traditional ORMs like TypeORM, MikroORM and Sequelize.


2 Answers

[{"userid": "test","password": "test"}]

This is an Array of Objects. So: First loop over the array to get a single object and then extract its properties:

for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    console.log(row.userid);
}
like image 52
TimWolla Avatar answered Sep 20 '22 16:09

TimWolla


Try this (this is really basic):

   connection.query('SELECT * from pass', function(err, rows) {
     res.json(rows);

     var user = rows[0].userid;
     var password= rows[0].password;

   });
like image 26
Tobi Avatar answered Sep 23 '22 16:09

Tobi