postgresql - Async instead of joins - am I cheating? -


i have been trying replicate async parallel set of queries using json_agg in postgres.

in heart, although async approach gets me results want, feel cheating , cause me pain in future.

below have included results current implementation. how achieve same json_agg?

express route

router.get('/', function(req, res) {     async.parallel({       records: function(parcb) {         var query = knex('records').select('title','id').orderby(knex.raw('random()')).limit(5)         query.then(function(results) {           parcb(null, results);         });       },       collections: function(parcb) {         var query = knex('collections').select('name','id').orderby('name')         query.then(function(results){           console.log(results)           parcb(null, results);         });       },     },     function(err, results) {       res.render('index.html', {         title: 'welcome',         data: results       });     });  }); 

output

{ collection:     { id: 31,      slug: 'bar',      name: 'barker',      long_name: 'barker',      copyright: '',      description: null,      notes: '',      createdat: tue jan 05 2016 16:47:35 gmt+0000 (utc),      updatedat: tue jan 05 2016 15:32:55 gmt+0000 (utc) },   records:     [ { title: 'whiddon down: general view, tawton, south',        id: 12595 },      { title: 'stoke in teignhead', id: 13937 },      { title: 'teign estuary', id: 104573 },      { title: 'lydford village', id: 106650 },      { title: 'metheral hut circle before submersion fernworthy reservoir',        id: 1467 } ] } 

first , foremost, don't mix async library , promises. avoids unnecessary pain.

if 1 of libraries use based on promises (like knex), i'd recommend ditch async, use proper promise library (one bluebird) , work it.

var promise = require('bluebird'); var knex = require('knex'); var express = require('express'); var router = express.router();  router.get('/', function(req, res) {   promise.all([     knex('records').select('title','id').orderby(knex.raw('random()')).limit(5),     knex('collections').select('name','id').orderby('name')   ]).then(function (results) {     res.render('index.html', {       title: 'welcome',       data: {         records: results[0],         collections: results[1]       }     });   }); }); 

i'm afraid can't lot json_agg here, though.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -