【问题标题】:How to retrieve added doc data in Firestore?如何在 Firestore 中检索添加的文档数据?
【发布时间】:2020-09-15 23:02:02
【问题描述】:

我有这样的代码,我可以在其中获取新插入的文档 ID:

db.collection("cities").add({
   name: "Tokyo",
   country: "Japan"
})
.then(function(docRef) {
   console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
   console.error("Error adding document: ", error);
});

是否可以从 ref 获取数据?

【问题讨论】:

标签: google-cloud-firestore


【解决方案1】:

是的,你可以这样做:

.then(function(docRef) {
   db.collection("cities").doc(docRef.id).get()
     .then(snap => {
        console.log('Here is the document you wrote to', snap.data()
      })
})

当然,它需要你可能不想要的另一次阅读

【讨论】:

    【解决方案2】:

    我找到了解决办法

    static async createUserPofile(uid) {
        const db = Firebase.firestore(),
            date = Firebase.firestore.FieldValue.serverTimestamp(),
            data ={
                user_id: uid,
                creation_time: date,
                update_time: date
            },
            docRef = await db.collection("user_profiles").add(data),
            get = await docRef.get();
        return get.data();
    }
    

    【讨论】:

    • 在下面@GrantSingleton 的回答中表达了添加后的想法。为什么不接受呢?另外,我看不到通过获取和返回.data() 可以获得什么。你不是已经有data = {...} 吗?
    • 啊,我明白了。对不起。我希望 add 会返回一个服务器时间戳。我认为要求编写的整个对象太过分了,因为在添加之后运行的触发器可能会改变它。无论如何,我赞成首先给出正确答案的本质。
    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2020-09-12
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多