【发布时间】: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