I have the following JSON stored on my local which I want to store it on Firebase Firestore:
guides: [
{
"id":0
"name":"name0",
"sources":[
{
"type":"s3",
"url":"https://s3.amazonaws.com/xxxx/file0.mp3"
}
]
},
{
"id":1
"name":"name1",
"sources":[
{
"type":"s3",
"url":"https://s3.amazonaws.com/xxxx/file1.mp3"
}
]
}
]
What is the best solution for store "sources"? so when I make a search for "guides" (using firebase cloud functions), it retrieves the source list as well without making different searchs for each element of sources.
In Firebase Firestore, the array type doesn't allow a list of objects and I tried with "reference" but it returns the "structure and settings" of the document which is referencing.
function getGuides(guideId,response){
db.collection('guides')
.where('id', '==', guideId).get()
.then(snapshot => {
let guideDoc = snapshot.docs.map( doc => {
return doc.data()
})
return guideDoc;
})
答案 0 :(得分:1)
在回答中,您说“在Firebase Firestore中,数组类型不允许对象列表”。
这是不正确的:您可以将对象存储在数组中。使用Firebase控制台,您必须首先选择阵列数据类型,然后为每个阵列成员选择映射类型。使用JavaScript SDK,您可以保存包含对象数组的文档。
基于上述情况,使用Firestore时可以采用以下方法:
guide
个文档guide
文档:
id
值作为文档ID; sources
,您可以在其中存储对象,例如在问题中显示的对象。这样,您可以按文档guides
查询id
并按以下方式获取数组:
var docRef = db.collection("guides").doc(guideId);
docRef.get().then(doc => {
if (doc.exists) {
const sourcesArray = doc.data().sources;
sourcesArray.forEach((element) => {
console.log(element.type);
console.log(element.url);
});
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});