[英]Efficient querying in Sequelize
I am implementing a post upvote system that limits by IP. 我正在实施一个通过IP限制的post upvote系统。 So far, the route for upvoting a single post contains 4 total queries in order to complete these steps:
到目前为止,提交单个帖子的路由包含4个总查询,以便完成以下步骤:
-otherwise- -除此以外-
I feel like the last two steps could be combined, however if I just return the post after associating the upvote to it, it is not included which makes sense because when it was found it had no upvote associated. 我觉得最后两个步骤可以组合在一起,但是如果我在将upvote关联到它之后返回帖子,则不包含它是有意义的,因为当它被发现它没有关联的upvote时。 Here is what I currently have and I feel it's very inefficient for a single upvote.
这是我目前所拥有的,我认为单一的upvote非常低效。
router.get('/posts/:id/upvote', function(req, res) {
var id = req.params.id;
var query_options = {
where: {
id: id
},
include: common_includes
};
// Look for already existing upvote with same PostId and IP.
Upvote.findOne({ where: { ip: req.ip, PostId: id }}).then(function(upvote) {
if (upvote !== null) return res.fail('Already upvoted');
// No upvote exists, create one
Upvote.create({
ip: req.ip
}).then(function(upvote) {
// Find post to associate upvote with
Post.findOne({ where: { id: id }}).then(function(post) {
// Associate upvote to post
upvote.setPost(post).then(function() {
// Query again to get updated post to be returned
Post.findOne(query_options).then(function(post) {
return res.pass(formatPost(post));
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
});
});
May be helpful http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations . 可能会有所帮助http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations 。
But IMHO you can combine step 2 and 3 with: 但恕我直言,你可以将第2步和第3步结合起来:
Upvote.create({
ip: req.ip,
PostId: id
})
and then fetch the new post 然后获取新帖子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.