【发布时间】:2018-10-04 19:28:01
【问题描述】:
我正在尝试使用 pg-promise 从节点中的 postgres 检索嵌套查询。
我只能从表中检索包含混合数据的简单非嵌套结果。
我想从三个表(用户、帖子、cmets)中为每个帖子获取一个数据集 - users.username、posts.text、post.timestamp、cmets.author、cmets.text、cmets.timestamp。用户和帖子与用户名关联,帖子和cmets与posts.id和cmets.parrent关联。
这是我要获取的数据:
[
{"username": "jane",
"postText": "Hello",
"postId": 4,
"postTimestamp: "1651156414",
allComments: [
{"commentsId": 2,
"commentsAuthor": "john",
"commentsText": "nice",
"commentsTimestamp": "156454565456"
},
{"commentsId": 3,
"commentsAuthor": "ghost",
"commentsText": "hiii",
"commentsTimestamp": "165165848"}]
}]
我正在使用 pg-promise:
function getUsers(t) {
return t.map('SELECT * FROM posts', post=> {
return t.map('SELECT * FROM users WHERE users.username = post.username', post.id, user => {
return t.any('SELECT * FROM comments, posts WHERE comments.parrent = post.id', user.id)
.then(comment => {
user.comment = comment;
return user;
});
})
.then(t.batch)
.then(user=> {
post.user = user;
return post;
});
}).then(t.batch);
}
db.task(getUsers)
.then(data => {
console.log(data)
res.send(data)
})
.catch(error => {
console.log(error)
});
});
它给了我错误:
TypeError: undefined is not a function at Array.map (<anonymous>) at obj.any.call.then.data
您有什么想法吗,我做错了什么?谢谢
【问题讨论】:
-
最好的建议 - 对这种嵌套结构使用 JSON 查询,使用
json_build_object函数,如下所示:stackoverflow.com/questions/39805736/…。性能会显着提高。
标签: javascript sql node.js postgresql pg-promise