[英]Retrieve document from Firestore using URL
I have a Firestore DB with this structure.我有一个具有这种结构的 Firestore 数据库。
-user [root collection]
--userid [doc]
--work [sub collection]
--documentID [document with required data]
I want users to be able to click a link they are given such as:我希望用户能够点击给他们的链接,例如:
mysite.com/work.html?work=documentID
This would open the page mysite.com/work.html and pull in the data from documentID to the page and display the data in the named document to the user.这将打开页面 mysite.com/work.html 并将 documentID 中的数据拉入页面并将命名文档中的数据显示给用户。
Alternatively, they could enter url of;或者,他们可以输入 url 的;
mysite.com/users/work/documentID.
and be displayed the same information.并显示相同的信息。
Users are always logged in before taking any actions.用户在采取任何行动之前总是先登录。 Stack is Firestore, Firebase Hosting, Node and Cloud Functions, jQuery.
堆栈是 Firestore,Firebase 托管,节点和云功能,jQuery。
I wonder if I am being very dumb, but I really can't work out how to get started to make this work - turning up a blank on all kinds of searches for how to do this, so I'd really appreciate some help!我想知道我是不是很笨,但我真的不知道如何开始做这项工作——在各种搜索如何做到这一点时出现空白,所以我真的很感激一些帮助!
You can approach this problem in following way -您可以通过以下方式解决此问题 -
When the user clicks on the link mysite.com/work.html?work=documentID
, create a router that will handle the given request.当用户单击链接
mysite.com/work.html?work=documentID
时,创建将处理给定请求的路由器。 Since the user is already logged in you can collect uid and documentId from the request.由于用户已经登录,您可以从请求中收集 uid 和 documentId。 In firestore you can refer to nested documents using the path something like
col/doc/subcollection
在 firestore 中,您可以使用
col/doc/subcollection
之类的路径来引用嵌套文档
Second create function to handle the route, that will retrive data from firestore, like so -其次创建 function 来处理路由,这将从 Firestore 中检索数据,如下所示 -
document_read.js document_read.js
const admin = require('firebase-admin');
admin.initializeApp
const db = admin.firestore();
async function readData(uid, docId){
const snapshot = await db.collection('users/${uid}/work').doc(docId).get();
const data = snapshot.data();
//Do something with your data and return results here
}
This function will return the data to the desired page that needs to display the details.这个 function 会将数据返回到需要显示详细信息的所需页面。
Finally you will need to protect the firestore data from unauthorized request with security rules, to allow only owners of the documents to read/writes the data -最后,您需要使用安全规则保护 Firestore 数据免受未经授权的请求,以仅允许文档所有者读取/写入数据 -
firestore rules火库规则
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
}
}
You can read more here.你可以在这里阅读更多。
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.