Firestore:在 Web v9 中添加新数据的模式是什么? [英] Firestore: What's the pattern for adding new data in Web v9?
问题描述
我在很多地方看到,访问嵌套文档和集合的模式类似于 db.collection("users").doc("frank").collection("pets")
等
I have seen in many places that to access nested documents and collections the pattern is something like db.collection("users").doc("frank").collection("pets")
etc.
这对我来说很有意义并且很容易理解.问题是,我的 (React) 项目是以 Web 版本 9 方式设置的.我一遍又一遍地梳理了文档,除了在 Y 集合中引用 X 文档之外,看不到任何内容.
This makes a lot of sense to me and is easy to understand. The trouble is, my (React) project is set up in the Web version 9 way. I've combed the docs over and over and can't see anything that goes beyond referencing X doc in Y collection.
我需要引用用户 >用户名>一些集合
I need to reference Users > uid > someCollection
但在 Web 版本 9 中我只能这样做:doc(db, "users", uid)
But in the Web Version 9 way I can only do: doc(db, "users", uid)
我如何更深入?
推荐答案
如果您想获得:
- a CollectionReference,然后使用
collection()代码>:
- a CollectionReference, then use
collection()
:
const myCol = collection(db, "collection", "doc1", "sub-col1")
- a DocumentReference,然后使用
doc()代码>:
- a DocumentReference, then use
doc()
:
const myDoc = doc(db, "collection", "doc1", "sub-col1", "sub-doc1")
概念保持不变.文档路径具有偶数个段,例如col/doc/sub-col/sub-doc
而集合的路径有 odd 例如col/doc/sub-col
.
The concept remains same. The path to a document has even number of segments e.g. col/doc/sub-col/sub-doc
while path to a collection has odd e.g. col/doc/sub-col
.
如果传入的参数数量无效,这两种方法都会抛出错误.
在命名空间版本 (v8) 中,它曾经看起来像:
In the name-spaced version (v8), it used to look like:
// DocumentReference
firebase.firestore().doc("col/doc/sub-col/sub-doc")
// CollectionReference
firebase.firestore().collection("col/doc/sub-col")
本质上,您不断向相同的 doc()
或 collection()
方法添加路径段.
In essence, you keep adding path segments to the same doc()
or collection()
methods.
doc(firestore: Firestore, path: string, ...pathSegments: string[]):
// You can also use spread operator with an array
扩展运算符示例:
An example with spread operator:
const myDocPath = "users/user1/posts/post1/comments/comment1"
const docRef = doc(db, ...myDocPath.split("/"))
如果将 spread operator
与 split()
一起使用,请确保没有任何前导或尾随斜线.
Just make sure you don't have any leading or trailing slash if using spread operator
with split()
.
这篇关于Firestore:在 Web v9 中添加新数据的模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!