Reputation: 137
I have a Firestore DB with this structure.
-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.
Alternatively, they could enter url of;
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.
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!
Upvotes: 2
Views: 1254
Reputation: 2270
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. Since the user is already logged in you can collect uid and documentId from the request. In firestore you can refer to nested documents using the path something like col/doc/subcollection
Second create function to handle the route, that will retrive data from firestore, like so -
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.
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 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!
Upvotes: 3