'Update DB with object and array in node js and pg-promise
I am creating a system to switch accounts without the need to log in every time, just once. For this I have a session variable, but in case there are 4 sessions, the first 2 with variable 1 and the rest with variable 2 and the user tries to connect all 4, the session variables must be updated again.
What I do is obtain the id of the rows that I want to update and I pass the variable that will remain for all the sessions, but I don't know how to do a where in with an object and an array, can you recommend a better solution.
This is an example, please ignore the connection is wrong.
DATABASE TABLE: | ID | ID_USER | ID_USER_RELATIONATED | ID_SESSION | | -- | ------- | -------------------- | ---------- | | 1 | 1 | 3 | 1 | | 2 | 1 | 4 | 1 | | 3 | 2 | 5 | 2 | | 4 | 2 | 6 | 2 |
const pgp = require('pg-promise')({});
const SessionData = {
ID_SESSION: 1,
ID: [3, 4]
};
let conecctionBD;
try {
conecctionBD = await pgp.connect();; //Obtener una conexión a la base de datos POSTGRESQL
const condition = pgp.as.format(' WHERE "ID" IN (${ID:csv})', SessionData);
let query = pgp.helpers.update(SessionData, null, 'SESSION') + condition;
let id = await conecctionBD.result(query, r => r.rowCount)
.then(count => {
return count
})
.catch(error => {
return error
});
if (id.rowCount > 0) {
return true
} else {
return false
}
}catch (error) {
let date = new Date();
console.error(`${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
=> Error: `, error);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
