[英]How to get the data of a user who created a document
I have two collections, one for registering properties and one for registered users.我有两个 collections,一个用于注册属性,一个用于注册用户。
The collection for registering properties is called listings
and the collection for registered users is called users
.注册属性的集合称为
listings
,注册用户的集合称为users
。
I access the documents inside the listings
collection using the parameter listingId
, which is the document ID.我使用参数
listingId
访问listings
集合中的文档,该参数是文档 ID。
I get the data from the document via the parameter I passed in:我通过传入的参数从文档中获取数据:
const fetchListing = async () => {
const docRef = doc(db, 'listings', listingId)
// response
const docSnap = await getDoc(docRef)
if (docSnap.exists) {
listing = docSnap.data()
}
}
I need to get the fields (name,email, twitter, etc..) of the user who created the document.我需要获取创建文档的用户的字段(名称、email、twitter 等)。 How do I do this?
我该怎么做呢?
Each document has the ID of the user who creates it.每个文档都有创建它的用户的 ID。
You have to do as follows:您必须执行以下操作:
data()
method , to get the user ID value (As explained in the doc, "this method retrieves all fields in the document as an Object").data()
方法返回的 Object 获取用户 ID 值(如文档中所述,“此方法将文档中的所有字段作为对象检索”)。data()
method).data()
方法)。 const fetchListing = async () => {
const docRef = doc(db, 'listings', listingId);
const docSnap = await getDoc(docRef);
if (docSnap.exists) {
const userId = docSnap.data().user;
const userDocRef = doc(db, 'users', userId);
const userDocSnap = await userDocRef(docRef);
if (userDocSnap.exists) {
const userName = docSnap.data().name;
const userEmail = docSnap.data().email;
// ...
}
}
};
Note that a common approach for your use case in the NoSQL world is to denormalize your data in such a way that you get all the necessary data in your front-end in a minimum number of queries.请注意,在 NoSQL 世界中,您的用例的一种常见方法是对您的数据进行非规范化处理,以便您以最少的查询次数在前端获取所有必要的数据。 Here is a "famous" post about NoSQL data-modeling approaches.
这是一篇关于 NoSQL 数据建模方法的“著名” 帖子。
More concretely it means that in each Listing doc you would duplicate the data of its author/creator.更具体地说,这意味着在每个列表文档中,您将复制其作者/创建者的数据。
One side effect of this approach is that you need to keep the values in sync (ie the one in the User document and the ones in the Listing documents).这种方法的一个副作用是您需要保持值同步(即用户文档中的值和列表文档中的值)。 This synchronization could be done with a Cloud Function triggered if the User doc is modified.
如果修改了用户文档,则可以通过触发 Cloud Function 来完成此同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.