[英]querying two tables in sequelize
there is surely some way to get this done in a lot less lines of code. 肯定有一些方法可以用更少的代码行来完成。
databases isn't my strongest and I'm new to sequelize and node. 数据库不是我最强的数据库,而我是新手。 The user id comes in as a parameter and I have to check if there is a user in the user table.
用户ID作为参数输入,我必须检查用户表中是否有用户。 If no user just send back no user otherwise check pics table to see if user has a pic.
如果没有用户只是发回,则没有用户,否则请检查图片表以查看用户是否有图片。 userid is forign key in pics table.
userid是pics表中的外键。 if user doesn't have a pic i give them a default other wise i set their pic as the stored one in the database.
如果用户没有图片,我给他们一个默认的其他方式,我将他们的图片设置为数据库中存储的图片。 I have it working but I know it can be written a lot better with less lines of code many using findAll and include but I cant get it.
我有它的工作,但我知道它可以用findAll和include更少的代码行来写得更好,但是我无法理解。 Any help appreciated.
任何帮助表示赞赏。 Here is the code that works..
这是有效的代码。
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.
肯定有一些方法可以用更少的代码行来完成。
You can put it all on one line if you minify it :D ! 如果将其最小化,可以将它们全部放在一行上:D!
Joking aside ... 开玩笑...
.findOne
function returns a promise . .findOne
函数返回一个promise 。
Unlike callbacks, with promsies, if there is an error thrown it will be caught by the accomanying catch function. 与回调不同的是,如果出现错误,则抛出的错误将被伴随的catch函数捕获 。 All you need to do is put the error in the catch and don't bother with first query.
您需要做的就是将错误放在陷阱中,不要打扰第一个查询。
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 }});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.