简体   繁体   English

将文档添加到 Firestore 中不存在的子集合

[英]Add a document to a non-existent subcollection in Firestore

Hope this isn't too obvious but I am really stumped at this point.希望这不是太明显,但在这一点上我真的很难过。 I am having trouble adding a document to a subcollection that does not exist in Firebase Firestore.我无法将文档添加到 Firebase Firestore 中不存在的子集合。

The code works perfectly when adding to a subcollection that already exists.添加到已经存在的子集合时,该代码可以完美运行。

db.collection("collectionId").doc(docId).collection("subcollectionId").doc(subdocId).collection("items").add({
    userName,
    isActive: true        
}).then(function() {
    console.log("Document successfully written!");
}).catch(function(error) {
    console.error("Error writing document: ", error);
});

To be clear here, the sub-sub-collection "items" exists in some of my sub-collections and has not yet been created in others.在这里要清楚,子子集合“项目”存在于我的一些子集合中,但尚未在其他子集合中创建。 When I attempt to add a document to "items" using the above code in a subcollection that already has other "items", it works with the following result:当我尝试在已经有其他“项目”的子集合中使用上述代码将文档添加到“项目”时,它会产生以下结果:

Document successfully written!

When I attempt to add a document to "items" in a subcollection where "items" does not exist, it does not add the item and there is nothing written to the console.当我尝试将文档添加到“items”不存在的子集合中的“items”时,它不会添加该项目并且没有任何内容写入控制台。

Thanks for the help in advance!我在这里先向您的帮助表示感谢!

UPDATE WITH SCREENSHOTS AS ASKED FOR:根据要求更新屏幕截图:

Success:成功: 在此处输入图片说明

Failure:失败: 在此处输入图片说明

When you write a document to any collection or subcollection that doesn't exist, it will then immediately exist.当您将文档写入任何不存在的集合或子集合时,它将立即存在。 This behavior never changes.这种行为永远不会改变。 The SDK will never give you an indicator of success without actually writing the document.如果不实际编写文档,SDK 永远不会为您提供成功的指标。

If you're saying that the document just doesn't get written, then it sounds like you're not looking in the right place.如果您是说文档没有写好,那么听起来您似乎没有找对地方。 Refreshing the Firebase or Cloud console in your web browser helps to reveal newly created collections.在 Web 浏览器中刷新 Firebase 或 Cloud 控制台有助于显示新创建的集合。 It will also help if you know exactly what the value of subdocId is here, so you know for sure where to look.如果您确切地知道subdocId的值是什么,它也会有所帮助,这样您就可以确定要查找的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM