在pg-promise中编写子查询的好方法

时间:2019-04-11 06:18:15

标签: node.js postgresql pg-promise

如果我必须以哪种方法在单个API中执行更多查询, 这是在主查询内编写子查询的更好方法 而不使用db.task或db.tx,否则我必须使用这些方法。 像这样

function userChangePassword(req, res) {
    const changePwd = req.swagger.params.body.value;

    const token = req.headers.authorization;
    token.replace('Bearer ', '');
    const decoded = jwt_decode(token);

    const newpass = changePwd.newPassword;
    const user_id = decoded.userId;

    const userSel = `select * from xx."yy" where "userId" = '${user_id}' AND "status" = 1`;
    const updatePwd = `update xx."yy" set "password" = '${newpass}' where "userId" = '${user_id}' `;

    db.query(userSel).then((usrResult) => {
            if (usrResult.length > 0) {
                db.query(updatePwd).then(() => {
                    res.send(response.success("The password has been changed successfully", []));
                });
            } else {
                res.send(response.success("The password has not changed successfully", []));
            }
        })
        .catch((err) => {
            if (util.isError(err)) res.error('NotFoundError', err); // return 404
            else res.error('InternalServerError', err); // else 500
        });
}    

请帮助我解决这种混乱的情况。 谢谢。

1 个答案:

答案 0 :(得分:2)

如果查询之间有依赖关系,则必须使用方法task / tx。否则,您可以使用helpers.concat将查询连接成一个查询,并将它们作为一个查询执行,这将更快。如果您希望从多查询返回数据,则可以使用方法multi / multiResult

相关问题