1

I have two tables and I need data in this format. How is this Possible?

My Tables

Required Output

{
  "id":"1",
  "name":"akhil",
  "pics": [
    {
      "pic1": "123.jpg",
      "pic2": "123.jpg"
    }
  ]
}

Generally I use this for getting data from single table

const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const config = require('./config');

var VerifyToken = require('./VerifyToken');

const mysql      = require('mysql');

app.use(express.json());
const connection = mysql.createConnection({
   host     : 'localhost',
   user     : 'root',
   password : 'password',
   database : 'sample'
});
    app.get('/usersdata', VerifyToken, (req, res) => {
       let id = req.userId;
       console.log(req.userId);
       connection.query("select * from users", function (error, results, fields) {
          if (error) throw error;
          else {
             res.send({"result": results});
          }
       });
    })
2
  • What is connection.query? What module are you using to access your database? Commented Apr 2, 2019 at 18:41
  • I am using mysql @JordanRunning Commented Apr 3, 2019 at 1:06

2 Answers 2

1

My Solution:

app.get('/usersdata', (req, res) => {
   connection.query("select u.id, u.name, p.pic1, p.pic2 from users u, pics p where u.usersid=p.id", function (error, results, fields) {
      if (error) throw error;
      else {
         let data = results;
         let newResult = {};
         results.map(row => {
            if(newResult[row.id]) {
               newResult[row.id].pics.push(row.pic1, row.pic2)
            } else {
               newResult[row.id] = { id: row.id, name: row.name, pics: [row.pic1, row.pic2] };
            }
         })
         res.send({ "result": Object.values(newResult) });
      }
   });
})
Sign up to request clarification or add additional context in comments.

Comments

0

I would use an ORM instead of writing query myself. Check this link used for a project saved lot of time and code was cleaner.

2 Comments

See this link for joining two tables in Sequelize
This is my client requirement and I cannot change it to some ORM @Bharath

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.