【问题标题】:How to Create a Firestore Subcollection and Add to It?如何创建 Firestore 子集合并添加到其中?
【发布时间】:2023-03-28 23:44:01
【问题描述】:

我一直在尝试创建一个函数,将输入的内容添加到 Firestore 集合文档,然后为该文档创建一个子集合,获取其余内容并将其放入该子集合中的文档中。但是,我遇到了一个问题,我可以添加到集合中,但不能创建并添加到子集合中。有没有什么办法解决这一问题?我的代码如下。

document.getElementById("submitButton").addEventListener("click", function() {
var storyTitle = document.getElementById("storyTitle").value;
  var chapterTitle = tinymce.get("writeTitle").getContent();
  var chapterContent = tinymce.get("chapterContent").getContent();
  const db = firebase.firestore();
              
  
  addStory(storyTitle,chapterTitle,chapterContent);
  
});
    
function addStory(story,chapter,theContent) {
  const db = firebase.firestore();
  const sub = db.collection("Stories").doc(story).collection("Chapters");
  //const docRef = db.collection("Stories").doc(storyTitle);
  document.getElementById("testing").innerHTML = story + ", " + chapter + ", " + theContent;

db.collection("Stories").doc(story).set({
    title: story
}).then(() => {
    console.log("Document successfully written!");
}).catch((error) => {
    console.error("Error writing document: ", error);
});

db.collection("Stories").document(story).collection("Chapters").add({
    title: chapter,
    content: theContent
}).then(() => {
    console.log("Document successfully written!");
}).catch((error) => {
    console.error("Error writing document: ", error);
});
    
}

【问题讨论】:

    标签: database firebase google-cloud-firestore


    【解决方案1】:

    我认为你应该这样做:

      const storiesRef = db.collection('Stories').doc(story).get();
      const chapterRef = storiesRef.collection('Chapters').doc();
    

    您可以使整个函数异步,这样您就可以等待设置/更新每个集合的相应值,如下所示:

     await storiesRef.set({
       title: story
     });
    
     await chapterRef.set({
       title: chapter,
       content: theContent
     });
    

    同时您可以在这里查看:https://firebase.google.com/docs/firestore/data-model。文档充分解释了如何创建子集合。

    我希望这会有所帮助。

    【讨论】:

    • 这是现在的功能,但它不起作用。异步函数 addStory(story,chapter,theContent) { const db = firebase.firestore(); document.getElementById("testing").innerHTML = "故事标题:" + 故事; const storiesRef = db.collection('Stories').doc(story).get(); const chapterRef = storiesRef.collection('Chapters').doc();等待故事Ref.set({标题:故事}); await chapterRef.set({ title: chapter, content: theContent }); }
    • 这看起来不错。如果您无法写入存储,请仔细检查以确保您具有读/写权限
    • 你检查权限了吗?设置正确吗?
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多