【发布时间】:2018-10-27 17:39:36
【问题描述】:
我是 node(express) 和 pg-promise 的新手,还无法弄清楚如何将每个嵌套查询(循环)的结果添加到主 json 数组结果查询中。
我有两个表:Posts 和 cmets。
CREATE TABLE post(
id serial,
content text not null,
linkExterno text,
usuario VARCHAR(50) NOT NULL REFERENCES usuarios(alias) ON UPDATE cascade ON DELETE cascade,
multimedia text,
ubicacation VARCHAR(100),
likes integer default 0,
time VARCHAR default now(),
reported boolean default false,
PRIMARY KEY (id) );
CREATE TABLE comment(
id serial,
idPost integer NOT NULL REFERENCES post(id) ON UPDATE cascade ON DELETE cascade,
acount VARCHAR(50) NOT NULL REFERENCES users(alias) ON UPDATE cascade ON DELETE cascade,
content text NOT NULL,
date date default now(),
PRIMARY KEY (id));
所以我想将每个 cmets 的结果添加到每个帖子并返回帖子。 我有这个,但不起作用:
con.task(t => {
return t.any('select *, avatar from post, users where user= $1 and user = alias ORDER BY time DESC LIMIT 10 OFFSET $2', [username, pos])
.then(posts => {
if(posts.length > 0){
for (var post of posts){
post.coments = t.any('select * from comment where idPost = $1 ', post.id);
}
}
});
}).then(posts => {
res.send(posts);
}).catch(error => {
console.log(error);
});
有什么建议吗? PD:我认为我的问题有点类似于这个: get JOIN table as array of results with PostgreSQL/NodeJS
答案:
选项 1(最佳选择):
通过 JSON 到 psql 进行单个查询(JSON 查询)
查看@vitaly-t 的回答
或
使用 ajax 异步获取嵌套数据。
选项 2:
function buildTree(t) {
return t.map("select *, avatar from publicacion, usuarios where usuario = $1 and usuario = alias ORDER BY hora DESC LIMIT 10 OFFSET $2", [username, cantidad], posts => {
return t.any('select * from comentario where idPublicacion = $1', posts.id)
.then(coments => {
posts.coments = coments;
console.log(posts.coments);
return posts;
});
}).then(t.batch); // settles the array of generated promises
}
router.get('/publicaciones', function (req, res) {
cantidad = req.query.cantidad || 0; //num de publicaciones que hay
username = req.session.user.alias;
con.task(buildTree)
.then(data => {
res.send(data);
})
.catch(error => {
console.log(error);
});
});
选项 3(异步):
try{
var posts = await con.any('select *, avatar from post, users where user = $1 and user = alias ORDER BY time DESC LIMIT 10 OFFSET $2', [username, q])
for (var post of posts){
post.coments = await con.any('select * from comment where idPublictcion = $1', post.id);
}
}catch(e){
console.log(e);
}
【问题讨论】:
-
实际上,最好的答案是这里通过 JSON 查询的第二个选项:stackoverflow.com/questions/39805736/…,因为它比其他任何东西都快得多,并且可以很好地扩展。并且
await代码在缩放方面将是最差的,因为它是同步的;) -
@vitaly-t 你说得对!谢谢你的时间! :)
-
查看更新,您可能会更喜欢它;)
标签: node.js postgresql express promise pg-promise