Home > Enterprise >  NodeJS - Getting users with array of Id's using MySql
NodeJS - Getting users with array of Id's using MySql

Time:09-16

Objective:

I am trying to get a list of users from a table based on the logged user. so far I got to collect all my user Id's in an array and now I would like to query all those users in a new list to display on the front end.

What I've made so far:

I am importing those functions from another file where they execute their queries.

    (async () => {
        const user = await getUser(db, "[email protected]")
        console.log(user)
        // Logs the user that is logged in (works)

        const friendIdList = await getFriendIds(db, user[0].id)
        console.log(friendIdList)
        // Logs logs an array with the user id's that are related (works)

        const friendList = await getFriends(db, friendIdList)
        console.log(friendList)
        // Can not work out how to implement that array of Id's in a query

    })()

The getUser and friendIdList works well, but I cannot work out how to implement that array of id's in the query below:

const getFriends = (db, list) => {
    return new Promise((resolve, list) => {
        db.query(
            "SELECT * FROM users WHERE id IN ?",
            list,
            (err, result) => {
                return err ? reject(err) : resolve(result)
            }
        )
    })
}

My end result would be to have an array of all the users and send back as a response to the FE.

Or should I rething this approach completely?

CodePudding user response:

Did you try put parenthesis aroud the question mark?

"SELECT * FROM users WHERE id IN (?)",

If this doesn't work maybe you wanna try to use a better ORM or spread the array inside the string (this could lead to sql injection)

`SELECT * FROM users WHERE id IN (${...list})`
  • Related