代码之家  ›  专栏  ›  技术社区  ›  Let Me Tink About It

如何获取firebase/google cloud firestore集合中最新添加的文档?

  •  1
  • Let Me Tink About It  · 技术社区  · 6 年前

    使用Web/JS平台,我希望检索添加到集合中的最新文档。

    1. 我怎样才能做到这一点?
    2. 保存数据时是否需要附加时间戳?
    3. 服务器是否在后台自动附加时间戳 doc.add() ?
    https://firebase.google.com/docs/firestore/query-data/get-data
    db
      .collection("cities")
      // .orderBy('added_at', 'desc') // fails
      // .orderBy('created_at', 'desc') // fails
      .limit(1)
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(doc => {
          console.log(doc.id, " => ", doc.data());
          // console.log('timestamp: ', doc.timestamp()); // throws error (not a function)
          // console.log('timestamp: ', doc.get('created_at')); // undefined
        });
      });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Let Me Tink About It    6 年前

    您可以尝试使用 onSnapshot 侦听更改事件的方法:

    db.collection("cities").where("state", "==", "CA")
        .onSnapshot(function(snapshot) {
            snapshot.docChanges().forEach(function(change) {
                if (change.type === "added") {
                    console.log("New city: ", change.doc.data());
                    //do what you want here!
                    //function for rearranging or sorting etc.
                }
                if (change.type === "modified") {
                    console.log("Modified city: ", change.doc.data());
                }
                if (change.type === "removed") {
                    console.log("Removed city: ", change.doc.data());
                }
            });
        });
    

    来源: https://firebase.google.com/docs/firestore/query-data/listen

    推荐文章