英文:
Retrieving Document with a Collection in Firestore returning 'Encountered two children with same key` Error
问题
以下是初始集合结构的翻译:
消息(集合)
- ADasjewj123asdej-SAasdadfsd1234(文档) // 一个uid + '-' + 另一个uid
- chat(集合)
- 文档列表,等等。
我正在尝试检索具有自定义标识符的“Messages”中的所有文档,代码如下:
async getAllData(){
let data = await firestore()
.collection('Messages')
.get()
return data.docs.flat().map(doc => ({
value: Object.values(doc.data()),
key: doc.id
}))
}
并且它会提示错误;我已尝试基于Firestore文档的各种其他方法,但每次都出现相同的问题,可能是文档使用的自定义标识符引起的吗?
谢谢!
英文:
Here is what the structure of the initial collection looks like:
Messages (collection)
- ADasjewj123asdej-SAasdadfsd1234 (document) // its one uid + '-' + other uid
- chat (collection)
- list of documents, etc.
I'm trying to retrieve all the documents within Messages
, which has the custom indentifier, via:
async getAllData(){
let data = await firestore()
.collection('Messages')
.get()
return data.docs.flat().map(doc => ({
value: Object.values(doc.data()),
key: doc.id
}))
}
and it prompts the error; I've attempted various other methods based on the Firestore documentation, and its the same issue every time, could it be the custom identifier that the document uses?
thanks!
答案1
得分: 1
问题出在你将 doc.data()
分配给 value
的方式上,导致错误信息 "遇到两个具有相同键的子项" 通常发生在文档中存在重复键时。
我建议你直接将 doc.data()
分配给 value
,而不使用 Object.values
,因为 doc.data()
已经是 Map 形式的。
根据你提供的集合结构,看起来你的集合名称是 Data
而不是 Messages
。
根据React Native Firebase ,你的更新后的代码应该类似于这样:
async getAllData() {
let data = await firestore()
.collection('Messages') // 如果是这样,请更新集合名称为 'Data'
.get();
return data.docs.map(doc => ({
value: doc.data(),
key: doc.id
}));
}
英文:
The issue is with the way you are assigning the doc.data()
to the value
as error message "Encountered two children with the same key" typically occurs when you have duplicate keys within a document.
So I will recommend you to directly assign the doc.data()
to the value
without using Object.values
as doc.data()
is already in the Map form.
And as per your collection structure you provided it looks like your collection name is Data
rather than Messages
.
As per React Native Firebase your updated code should look something like this :
async getAllData() {
let data = await firestore()
.collection('Messages') // Update the collection name to 'Data' if that’s the case
.get();
return data.docs.map(doc => ({
value: doc.data(),
key: doc.id
}));
}
Reference : React Native Firebase
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论