flutter 如何用firebase读取收藏库中最近文档?

wmvff8tz  于 2023-01-02  发布在  Flutter
关注(0)|答案(3)|浏览(144)

The Product A,B's doc is in The collection[Product]. Also each product has their review collection. and User's review is updated in form of doc in that review collection
我正在做一个产品展示应用程序。用户可以为每个产品写评论。我正在尝试创建一个“最近写的评论”小部件“不管产品”。
我知道我需要根据时间戳获取文档。但是包含文档的集合都是不同的。如果无法同时阅读两个集合,我应该怎么做?您通常如何制作这个小部件?我认为,获取所有集合、合并它们并根据时间戳对其进行排序的成本太高了。
(目前,我将数据结构化为图片。)我所考虑的是,
先在doc('product A')中设置用户A的单据路径,以后用户B写评论时,reference字段值更新为用户B的路径。
还有比这更有效的方法吗?请给予我一个好的答案,谢谢你阅读并回答这个问题!

ruarlubt

ruarlubt1#

获取所有集合的第一个文档(默认反向顺序)

通过时间比较获取最近的

llmtgqce

llmtgqce2#

看起来你认为这是复杂的,这就是为什么你陷入这种情况。
您需要简化收集的审查。您正在创建不同的收集每一个产品,但你只需要一个表,使您的查询将是相同的和容易的。

在这里你可以使用相同的评论集合/表来保存所有用户对所有产品的评论。使用这种结构你可以很容易地按产品、按用户和按评论的用户/产品来获得评论。
然后你只需要运行一些命令,比如在reviews collection上运行以下命令,就可以获得product 1的最新评论。

db.collection("reviews").
  .where("ProductId", "==", "1")
  .orderBy("CreateDate", descending: true)
  .limit(3);
roqulrg3

roqulrg33#

看起来云函数可以解决你的问题。下面的代码将所有的评论合并到一个集合中,这样你就可以为你的小部件查询它了。

exports.manageReviews = functions.firestore.document('/Products/{productId}/Reviews/{userId}').onWrite(async (change, context) => {
// This cloud function listens to any review write or change by any user

const after = change.after.data(); // The document after the change
const userId = context.params.userId;
const productId = context.params.productId;

// Use this to make sure you have only the final review for each product
await admin.firestore().collection("AllReviews").doc(productId).set(after)


 // Alternatively use this to consolidate all reviews of all products in a single table
await admin.firestore().collection("AllReviews").add(after);

  //After that just query the collection AllReviews according to timestamp.
});

它可能需要一些调整,以适应您的需要。

相关问题