Home > Blockchain >  how to read recent document in collection with firebase?
how to read recent document in collection with firebase?

Time:12-30

Something like this

Here you can use the same review collection/table to save review of all products by all users. Using this structure you can easily get reviews by product, reviews by users and users/products by reviews.

Then you just have to run some command like following on reviews collection to get the latest review of product 1.

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

CodePudding user response:

Looks like a cloud function would solve your problem. The following code consolidates all reviews into a single collection so you could query that for your widget.

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.
});

It might require some tweaking to suit your needs.

  • Related