Querying Firestore Data based on FieldValue.serverTimestamp() - Date Condition

时间:2018-09-22 22:50:48

标签: angular firebase google-cloud-firestore

In my Angular & Firebase Web App, I store document creation date as Firestore server timestamp with below;

firestore.FieldValue.serverTimestamp()

I just want to query documents which created before 6 months from now (Firestore Server "now")

As I see Data type of this field is FieldValue and can not be converted to Javascript Date object.

this.afs.collection<MyObject>("myCollection",
            ref => ref.orderBy("createdAt", "desc")
              .where("user_id", "==", `${user.uid}`)
              .where("createdAt", ">", "?????")).valueChanges();

What should I need to put into question marks to query those documents which created after 6 months from now?

Thanks.

1 个答案:

答案 0 :(得分:0)

您可以尝试这段代码,我还没有真正运行过,但是我认为这个主意是这样的。

let start = firestore.FieldValue.serverTimestamp(); //start date 
var end= new Date(year, month, day);
end.setMonth(end.getMonth() + 6); //date 6 months from start

this.afs.collection<MyObject>("myCollection",
        ref => ref.orderBy("createdAt", "desc")
          .where("user_id", "==", `${user.uid}`)
          .where("createdAt", ">", "start"))
          .where("createdAt", '<', end).valueChanges();

希望有帮助。