javascript - 在sequelize中查询两个表

标签 javascript node.js sequelize.js

肯定有某种方法可以用更少的代码行来完成此任务。

数据库不是我最擅长的,而且我对sequelize和node还很陌生。用户 ID 作为参数传入,我必须检查用户表中是否有用户。如果没有用户,则发送回没有用户,否则检查图片表以查看用户是否有图片。 userid 是 pics 表中的外键。如果用户没有图片,我会给他们一个默认图片,否则我将他们的图片设置为数据库中存储的图片。我可以使用它,但我知道它可以用更少的代码行编写得更好,许多代码使用 findAll 和 include 但我无法得到它。任何帮助表示赞赏。这是有效的代码..

users.findById(userId)
    .then(function (user) {
        if (!user) {
            res.render('error', {
                message: 'No user found with id of ' + userId,
                error: {
                    status: 404
                }
            });
        } else {
            pics.findOne({
                where: {
                    user_id: userId
                },
                attributes: ['profile_pic_filename']
            }).then(function (pic) {
                if (!pic) {
                    //if no pic give a default
                    profilepic = process.env.DEFAULT_PROFILE_PIC;
                } else {
                    profilepic = CDNPath + pic.profile_pic_filename;
                }

                res.render('user', {
                        profilePic: profilepic,
                        firstname: user['first_name'],
                        username: user['username'],
                        surname: user['surname'],
                        email: user['email']}
                );
            });
        }
    });

最佳答案

there is surely some way to get this done in a lot less lines of code.

如果你缩小它,你可以把它全部放在一行上:D!

开个玩笑......

.findOne 函数返回一个promise

与回调不同的是,使用promsies,如果抛出错误,它将被附带的catch函数捕获。您需要做的就是将错误放入 catch 中,而不必担心第一个查询。

pics.findOne({ where: { user_id: userId }, attributes: ['profile_pic_filename']})
    .then(pic => {
        var profilepic = process.env.DEFAULT_PROFILE_PIC;
        if (pic) profilepic = CDNPath + pic.profile_pic_filename;

        res.render('user', {
            profilePic: profilepic,
            firstname: user['first_name'],
            username: user['username'],
            surname: user['surname'],
            email: user['email']}
        );
    })
    .catch(e => {
        // test the error is what you were expecting.
        return res.render('error',
            { message: 'No user found with id of ' + userId, error: { status: 404 }});
    });

关于javascript - 在sequelize中查询两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014453/

相关文章:

javascript - 无法从 $().data() 内到达 $(this)

node.js - 如何在 AWS 上使用 SSL 创建 node.js 应用程序?

node.js - 作为系统进程启动新进程

javascript - Sequelize : difference of DataTypes and Sequelize

javascript - jquery数据表: page length select list not shown

javascript - 如何在鼠标悬停时展开/折叠 Shiny 的仪表板侧边栏?

javascript - IE 和 setInterval() 不刷新/更新的问题

php - Socket.io私信通知

node.js - mocha,用于 nodejs 中的 post 的 chai 测试

javascript - SequelizeJS HasOne 关联错误