Database 如何创建Firestore子集合并添加到其中?
我一直在尝试创建一个函数,将输入的内容添加到Firestore集合文档中,然后为该文档创建一个子集合,获取其余内容并将其放入该子集合中的文档中。但是,我遇到了一个问题,我可以添加到集合中,但不能创建并添加到子集合中。有办法解决这个问题吗?我的代码如下Database 如何创建Firestore子集合并添加到其中?,database,firebase,google-cloud-firestore,Database,Firebase,Google Cloud Firestore,我一直在尝试创建一个函数,将输入的内容添加到Firestore集合文档中,然后为该文档创建一个子集合,获取其余内容并将其放入该子集合中的文档中。但是,我遇到了一个问题,我可以添加到集合中,但不能创建并添加到子集合中。有办法解决这个问题吗?我的代码如下 document.getElementById("submitButton").addEventListener("click", function() { var storyTitle = document
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);
});
}
以下是我认为你应该做的:
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
});
同时,您可以在这里查看:。这些文档充分说明了如何创建子集合
我希望这能有所帮助。这是函数,但它现在不起作用。异步函数addStory(story,chapter,theContent){const db=firebase.firestore();document.getElementById(“testing”).innerHTML=“story Title:”+story;const storiesRef=db.collection('story').doc(story).get();const chapterf=storiesRef.collection('Chapters').doc();wait storiesRef.set({Title:story});wait chapterf.set({title:chapter,content:theContent});}这看起来不错。如果您无法写入存储,请仔细检查以确保您具有读/写权限您是否检查了权限?它们是否正确设置?