For example I want to get the user info, emails and it's roles from db and create an object like :
{
"id": 1,
"firstname": "John",
"lastname": "Johnny",
"emails": [
{
"type": "work",
"email": "[email protected]"
},
{
"type": "personal",
"email": "[email protected]"
}
],
"roles": [
{
"role": "ADM",
"title": "Admin"
},
{
"role": "PUB",
"title": "Publisher"
}
]
}
There are three tables I need to query:
Users
table hasid
,firstname
,lastname
.Emails
table hastype
,email
,user_id
.Roles
table hasrole
,title
,user_id
.
Based on the pg-promise's wiki I am almost sure it has to be done using Tasks but not sure how would you chain them.
UPDATE In my actual project I had to insert a product and use the generated id to insert attributes. Adding my code here in case you have a similar situation:
//Insert a new product with attribites as key value pairs
post_product_with_attr: function(args) {
return db.task(function(t) {
return t.one(sql.post_new_product, args)
.then(function(dt) {
var queries = [];
Object.keys(args).forEach(function(key) {
queries.push(t.one(sql.post_attr_one, { Id: dt.id, key: key, value: args[key] }));
});
return queries.length ? t.batch(queries) : [dt];
});
});
}
Loose request outside an expired connection.
at pg-promise/lib/query.js line 183reject(errMsg);
– Leggy(queries > 0)
is an invalid piece of code. Should be(queries.length > 0)
, or simply:return queries.length? t.batch(queries) : [dt];
. That's why it fails there, as you never executet.batch(queries)
. – Malefaction