How to retrieve particular field values from MySQL table using Node.js

I’m working with a MySQL database that contains user information including usernames and pin codes. I need to locate a specific user by their username and then display their associated pin number. Right now I can check if the user exists but I’m not sure how to extract just the pin value from the query results.

Here’s my current approach for checking user existence:

dbConnection.query("SELECT * FROM users WHERE username = ?", ['user123456'], function(error, rows, fields){
    if(rows.length === 0){
        console.log("User not found");
    } else {
        console.log("User found");
        // How do I get the pin value here?
    }
});

What’s the best way to access the specific column data from the result set?

To retrieve the pin number for a specific user, you can access the pin value directly from the first object in your rows array after verifying that the user exists. Instead of selecting all fields with SELECT *, it’s more efficient to directly query the pin number. Here’s how your code should look:

dbConnection.query("SELECT pin FROM users WHERE username = ?", ['user123456'], function(error, rows, fields){
    if(rows.length === 0){
        console.log("User not found");
    } else {
        console.log("User found");
        const pinValue = rows[0].pin;
        console.log("Pin:", pinValue);
    }
});

This way, you minimize the data retrieved and can directly access the pin.