插入后如何通过ID获取文档?

时间:2018-01-16 16:31:01

标签: javascript firebase google-cloud-firestore

这个想法很简单。用户正在向集合添加新文档,然后想要在页面上列出它而不刷新。我知道我可以将所有备忘录与#include <stdio.h> #include <stdlib.h> int matrix_create(int ***m, int ze, int sp); void matrix_init(int **m, int ze, int sp); int main (void) { int ze = 3; int sp = 3; int i,j; int ***m = malloc(sizeof(int**)); *m = malloc(ze * sizeof(int*)); matrix_create(m, ze, sp); matrix_init(*m, ze, sp); for(i = 0; i < ze; ++i) { for(j = 0; j < sp; ++j) printf("%i\n", *m[i][j]); } return 0; } int matrix_create(int ***m, int ze, int sp) { int i, k; if (!*m) return 0; for (i = 0; i < ze; ++i) { *m[i] = malloc(sp * sizeof(int)); if (!*m[i]) { for (k = 0; k < i; ++k) free(*m[k]); free(*m); return 0; } } return 1; } void matrix_init(int **m, int ze, int sp) { int i,j; for(i = 0; i < ze; ++i) { for(j = 0; j < sp; ++j) m[i][j] = rand() % 1000; } } 同步,但这有点大不了,现在我只想通过onSnapshot获取插入的文档。

&#13;
&#13;
ID
&#13;
&#13;
&#13;

函数addWish = function() { let wish = document.getElementById("wish-text").value; if (wish && this.checkSignedIn()) { this.database.collection("wishes").add({ wish: wish, author: this.user.name, date: 0 - Date.now(), voteup: 1, votedown: 0 }).then(function(docRef) { console.log("Document written with ID: ", docRef.id); this.database.collection('wishes').doc(docRef.id).get().then(function (documentSnapshots) { this.renderWishes(documentSnapshots, 1); }.bind(this)).catch(function(error) { console.error("Error getting document: ", error); }); }.bind(this)).catch(function(error) { console.error("Error adding document: ", error); });在第一行之一失败。然后其他一切都失败了,例如renderWishes

foreach
  

获取文档时出错:TypeError:无法读取   财产&#39; 0&#39;未定义的

并且

  

foreach`:&#34; firebase.js:131获取文档时出错:TypeError:   querySnapshot.forEach不是函数

有没有机会解决这个问题?或者从Firestore获取ID无法获取文档?

1 个答案:

答案 0 :(得分:2)

异步get()操作的结果是返回的对象与您在代码中预期的对象不同。

在您的代码中,您将以下对象放入新文档中:

    {
        wish: wish,
        author: this.user.name,
        date: 0 - Date.now(),
        voteup: 1,
        votedown: 0
    }

当您在add()之后立即得到()该文档时,您调用querySnapshot的变量将包含一个DocumentSnapshot,其中包含这些内容。您正在尝试访问,DocumentSnapshot没有docs属性。这就是为什么你得到一个关于它未定义的错误。 DocumentSnapshot有一个id property,它将为您提供刚刚提取的文档的ID。

相关问题