node.js - 使用 pg-promise 进行嵌套查询对象映射

标签 node.js pg-promise

我正在查看 pg-promise 中的示例对于方法map :

// Build a list of active users, each with the list of user events:
db.task(t => {
    return t.map('SELECT id FROM Users WHERE status = $1', ['active'], user => {
        return t.any('SELECT * FROM Events WHERE userId = $1', user.id)
            .then(events=> {
                user.events = events;
                return user;
            });
    }).then(t.batch);
})
    .then(data => {
        // success
    })
    .catch(error => {
        // error
    });

假设 Event 实体与例如具有一对多关系。 汽车,我想列出连接到每个事件的所有汽车,我该如何使用map当我想要的对象深度超过一层时函数?

我想要的结果可能是这样的:

[{
    //This is a user
    id: 2,
    first_name: "John",
    last_name: "Doe",
    events: [{
        id: 4,
        type: 'type',
        cars: [{
            id: 4,
            brand: 'bmw'
        }]
    }]
}]

最佳答案

我是 pg-promise 的作者.

<小时/>
function getUsers(t) {
    return t.map('SELECT * FROM Users WHERE status = $1', ['active'], user => {
        return t.map('SELECT * FROM Events WHERE userId = $1', user.id, event => {
            return t.any('SELECT * FROM Cars WHERE eventId = $1', event.id)
                .then(cars => {
                    event.cars = cars;
                    return event;
                });
        })
            .then(t.batch) // settles array of requests for Cars (for each event)
            .then(events => {
                user.events = events;
                return user;
            });
    }).then(t.batch); // settles array of requests for Events (for each user)
}

然后使用它:

db.task(getUsers)
    .then(users => {
        // users = an object tree of users->events->cars
    })
    .catch(error => {
        // error
    });

方法map简化了将检索到的行映射到其他内容的过程,并且由于我们将它们映射到 promise 中,因此需要解决这些问题,为此我们使用方法 batch 。我们对汽车的每个内部请求数组执行此操作,然后在顶层 - 解决事件的请求数组。

更新

如果将树逻辑颠倒过来,可能会更容易阅读和维护:

function getUsers(t) {
    const getCars = eventId => t.any('SELECT * FROM Cars WHERE eventId = $1', eventId);

    const getEvents = userId => t.map('SELECT * FROM Events WHERE userId = $1', userId, event => {
        return getCars(event.id)
            .then(cars => {
                event.cars = cars;
                return event;
            });
    }).then(t.batch);

    return t.map('SELECT * FROM Users WHERE status = $1', ['active'], user => {
        return getEvents(user.id)
            .then(events => {
                user.events = events;
                return user;
            });
    }).then(t.batch);
}
<小时/>

还有一种更快的单查询方法,可以在这里找到:

关于node.js - 使用 pg-promise 进行嵌套查询对象映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273308/

相关文章:

node.js - 如何在不重启服务器的情况下编辑和部署代码?

javascript - 使用 Node.js 下载 Steroids.js

javascript - Pg-promise - 可能参与事务/任务的可重用查询

javascript - 如何正确 stub 作为另一个 Promise 一部分的 Promise 对象

postgresql - 带有 pg-promise 的 Postgres LISTEN/NOTIFY

javascript - node-mysql connection.query() 返回未定义

node.js - 如何在 Express 中处理二进制 post 数据?

javascript - 请求 SQL 2 左外连接

node.js - pg-promise 助手 : optionnal fields in insert and multiple-update

node.js - 如何使用 pg-promise 在没有密码的情况下连接到 Postgres 数据库?