【问题标题】:How to get document by ID after insertion?插入后如何通过ID获取文档?
【发布时间】:2018-01-16 16:31:01
【问题描述】:

这个想法很简单。用户正在将一个新文档添加到集合中,然后希望在页面上看到它而不刷新。我知道我可以将所有文档与onSnapshot 同步,但这有点大不了,现在我只想通过ID 获取插入的文档。

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:

renderWishes = function(querySnapshot, type) {
    console.log(querySnapshot.docs[0].data());
    querySnapshot.forEach(function(doc) {
        let id = doc.id;
        doc = doc.data(); //and after I simply display data with templates ${doc.author}

获取文档时出错:TypeError:无法读取 未定义的属性“0”

还有

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

有没有机会解决这个问题?还是无法通过 ID 从 Firestore 获取文档?

【问题讨论】:

  • querySnapshot 的唯一实例显示在失败的 console.log() 调用中。你在哪里准确定义它?
  • @Álvaro González 已更新。它被转移到函数中。我知道它实际工作的方式是因为有另一个函数可以正确刷新所有文档,但是当我尝试通过 ID 获取一个时,我得到一个错误。
  • 您似乎缺少一些代码。第一行以 .then() 开头。在它之前的调用是什么产生了你想要响应的承诺?
  • @Doug Stevenson 我跳过了那个,因为直到console.log("Document written with ID: ", docRef.id); 的所有内容都运行良好,我在控制台中看到了该 ID。但我不能用它来进一步。我用额外的代码更新了这个问题。如果您需要更多,我会提供更多,我不确定到底需要什么。我认为问题很明显并且位于中间的某个地方,但这似乎要复杂得多......
  • 我有一种感觉,您在那里只能访问一个文档。您可以尝试在您的renderWishes 中使用console.log(querySnapshot.data()); 而不是console.log(querySnapshot.docs[0].data()); 吗?

标签: javascript firebase google-cloud-firestore


【解决方案1】:

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

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

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

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

【讨论】:

  • 但是解决办法是什么? console.log(documentSnapshots); 的输出看起来很吓人,里面有很多东西,而我无法得到我需要的东西,比如 documentSnapshots.wishdocumentSnapshots.doc.wish。另外,您答案中的文字有点奇怪,所以我可能错过了实际的解决方案...
  • 对不起,我有一些不正确的信息。我更新了答案。
  • 哦,我明白了。所以我不能以这种方式得到任何东西,但 id ?那么获取该新消息的唯一两种方法是使用onSnapshot 还是通过HTTP 函数?或者刷新。
  • 查看我为 DocumentSnapshot 链接的文档,看看它还能为您提供什么。有一个 data() 方法可以为您提供文档的内容。这就是做 get() 的全部意义所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
相关资源
最近更新 更多