在Firestore中使用集合检索文档时返回’遇到两个具有相同键的子项’错误。

huangapple go评论66阅读模式
英文:

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
  }));
}

参考: React Native Firebase

英文:

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

huangapple
  • 本文由 发表于 2023年5月15日 06:59:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定