gpt4 book ai didi

javascript - 远程方法中相关模型的多次查询

转载 作者:行者123 更新时间:2023-11-29 21:14:47 24 4
gpt4 key购买 nike

我是 nodejs 和 Loopback/Express 的新手。我正在尝试编写一个涉及 API 调用的简单应用程序,该应用程序具有相关模型的多个数据库请求,但我找不到任何相关文档或示例来说明这一点。

假设有 3 个模型:作者、帖子和评分。每个帖子都有一个作者并且有很多评级。 Ratings 有一个称为“stars”的整数值。

我正在为名为“详细信息”的帖子创建一个自定义 API remoteMethod,它应该返回以下所有内容:

  • 发布详细信息
  • 作者详细信息(存储在相关作者模型中)
  • 有星级的相关评分数==1
  • 有星级的相关评分数==2
  • 有星级的相关评分数量==3

以最少和更多的数据库查询并行数来实现这个的最佳方法是什么?我已经使用 Promises 尝试了以下代码,但本质上它是一个低效的同步代码,对数据库进行了多次不必要的查询,并且很快变得非常困惑。

Post.details = function(id, cb) {

var LoopBackContext = require('loopback-context');
var app = require('../../server/server');
var Author = app.models.Author;
var Rating = app.models.Rating;

var response = {post: null,
author: null,
ratings_0: null,
ratings_1: null,
ratings_2: null
};

Post.findById(id, {include: 'author', where: {deleted: false}})
.then(function(p) {
response.post = p;
return Author.findById(p.authorId);
})
.then(function(r) {
response.author = r;
return Rating.find({where: {postId: id, stars: 0}});
})
.then(function(r) {
response.votes_0 = r.length;
return Rating.find({where: {postId: id, stars: 1}});
})
.then(function(r) {
response.votes_1 = r.length;
return Rating.find({where: {postId: id, stars: 2}});
})
.then(function(r) {
response.votes_2 = r.length;
cb(null, response);
});

};

对于这样一件微不足道的事情来说,这太过分了。我也尝试在查询中使用“include”,但它也变得难以使用,而且它不支持 Loopback 中的 2 级过滤器。

实现它的最佳方法是什么?

最佳答案

稍加重构和更改,它将变得非常简短明了:

Post.details = function(id) {
var app = require('../../server/server');
var Rating = app.models.Rating;

return Promise.all([
Post.findById(id, {include: 'author', where: {deleted: false}}),
Rating.count({ where: {postId: id, stars: 0}}),
Rating.count({ where: {postId: id, stars: 1}}),
Rating.count({ where: {postId: id, stars: 2}}),
]).then([post, ratings_0, ratings_1, ratings_2]) => {
return {
post,
author: post.author,
ratings_0,
ratings_1,
ratings_2,
};
});
};

这里发生了一些事情:

  • 您不需要 Author.findById,假设 include: 'author' 涵盖了它。
  • 至于评分计数,您刚刚使用了 Rating.count 方法。它会更快,因为使用的带宽更少,如果有索引,数据库可以更快地提供数据,因为它将直接从索引提供。
  • 我使用过 ES6 析构、对象字面量速记和箭头函数。
  • 如果您在环回远程方法中返回 promise ,它将使用方法返回值作为请求响应而不是回调。
  • Promise.all 将并行运行查询,并在所有给定查询完成后结束。

关于javascript - 远程方法中相关模型的多次查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39886540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com