1

I was trying to return a JSON Object but instead it returns an array. I am using primary key for query so I am sure I will only get one result.

This is my approach :

router.get("/student_info/:id", (req, res, next) => {
    connection.getConnection((error, currentConnection) => {
        if (!!error) {
            console.log("Error occurred while connecting db")
        } else {
            let id = req.params.id;
            currentConnection.query("SELECT * FROM students WHERE id=" + "'" + id + "'", (error, rows, fields) => {
                if (!!error) {
                    console.log(error.message)
                } else {
                    res.status(200).json(rows);
                }
                currentConnection.release();
            });
        }
    });
});

What I want is this :

    {
        "id": "171-15-8966",
        "name": "Alif Hasnain",
        "course_code": "CSE412,CSE413"
    }

But I get the result like this :

[
    {
        "id": "171-15-8966",
        "name": "Alif Hasnain",
        "course_code": "CSE412,CSE413"
    }
]

3 Answers 3

1

Just get the first element of the array before the json transformation:

res.status(200).json(rows[0]);
Sign up to request clarification or add additional context in comments.

Comments

1

By default query return the array of rows reflected by the select query. Since your query has single result it returns as array of single object to user.

You can change it to

res.status(200).json(rows[0]);

Please let us know if got better alternate.

Comments

0

Try this, using nested array destructuring

res.status(200).json([[rows]]);

You can read this blog to learn more about ES6 - Destructuring

ES6 - Understanding Destructuring

Comments

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.