Firestore: What's the pattern for adding new data in Web v9?
If you are trying to get:
- a CollectionReference, then use
collection()
:
const myCol = collection(db, "collection", "doc1", "sub-col1")
- a DocumentReference, then use
doc()
:
const myDoc = doc(db, "collection", "doc1", "sub-col1", "sub-doc1")
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
.
Both the methods will throw an error if invalid number of parameters are passed.
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")
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("/"))
Just make sure you don't have any leading or trailing slash if using spread operator
with split()
.
Firebase 9 - How to do new doc ref
The doc()
method is equivalent to .collection('users').doc('docID')
where you need to specify the ID. If you are trying to add a document with random ID then you add use addDoc()
with collection()
as shown below:
const usersCol = collection(db, 'Users')
await addDoc(usersCol, {...data})
If you want the random ID before adding the document then you can try this:
const userRef = doc(collection(db, 'Users'));
console.log(userRef.id)
Document references must have an even number of segments, but Users has 1.
You can checkout this answer for explanation of doc()
and collection()
:
Firestore: What's the pattern for adding new data in Web v9?
How to create a custom id document in firestore(Firebase modular SDK (v9))
You can use setDoc()
method to specify an ID instead of addDoc
which will generates a random ID as mentioned in the documentation:
const adminRef = doc(firestore, 'admin', collegeId);
// doc --->^
await setDoc(adminRef, {email: adminEmail, id: collegeId}) // overwrites the doc if it already exists
// ^^^
Also note that to create a DocumentReference you need to use doc()
and not collection()
which is used to create a CollectionReference. I've explained difference in these 2 here: Firestore: What's the pattern for adding new data in Web v9?
How do you create a new Firestore document within a transaction
If you are specifying the document ID (and not using the auto-generated IDs) then you must use doc()
instead of collection()
to create a DocumentReference:
const newLogRef = doc(db, 'transactionLogs', transactionLog.timeStamp);
The collection()
function is used create a CollectionReference.
Also checkout: Firestore: What's the pattern for adding new data in Web v9?
My understanding is that
transaction.set
will create a new record if the supplied reference doesn't exist
If the documents exists, the it'll overwrite the existing document.
Fetch Single Data by Document Id Reactjs Firebase Web SDK 9
You can use getDoc()
function to fetch a single document as shown below:
import { doc, getDoc } from "firebase/firestore";
useEffect(() => {
const fetchDocById = async () => {
// Create DocumentReference
const docRef = doc(db, "reports", id) // db = getFirestore()
// Fetch document
const docSnap = await getDoc(docRef)
if (snapshot.exists()) {
setUser({
...snapshot.val()
});
} else {
setUser({});
}
}
fetchDocById()
}, [id]);
Also checkout: Firestore: What's the pattern for adding new data in Web v9?
Firebase - How can i get data from reference?
If you have the DocumentReference
already then you can use getDoc()
function to retrieve the document from Firestore as shown below:
import { getDoc, DocumentReference } from "firebase/firestore";
export const getClubById = async (clubDocRef: DocumentReference) => {
const clubSnapshot = await getDoc(clubDocRef);
return clubSnapshot.data();
}
// Pass the reference itself to the function instead of doc ID
const club = await getClubById(userData.selectedClub)
For the error in the question, to create a DocumentReference
, if you have the document ID then you should doc()
function instead of collection()
that is used to create a CollectionReferencce
as shown below:
const docRef = doc(db, 'clubs', clubID);
Also checkout: Firestore: What's the pattern for adding new data in Web v9?
Firebase new namespace for .where() .limit() .orderBy()
Almost every Firebase method is a top-level function in Modular SDK and can be imported directly from the relevant SDKs. Try refactoring the code as shown below.
import { collection, getDocs, query, where, limit, orderBy } from "firebase/firestore";
const getDB = async () => {
const colRef = collection(db, "collection");
// Keep adding query clauses in query()
// like chaining them in name-spaced V8 version
const q = query(colRef, where("field", "==", "value"), limit(1));
const data = await getDocs(q);
console.log(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
}
The name-spaced version of the same query for reference:
const q = db.collection("col").where("field", "==", "value").limit(1);
You can find list of all functions in the new Firestore SDK in the documentation.
Also checkout:
- Order and limit data with Cloud Firestore (Refer to Modular tab in Documentation)
- Perform simple and compound queries in Cloud Firestore
- Firestore: What's the pattern for adding new data in Web v9?
- Firestore conditional where clause using Modular SDK v9
Related Topics
How to Calculate 3D Rotation on X and Y Axis from a 4X4 Matrix
Finding Element's Position Relative to the Document
How to Set a Js Object Property Name from a Variable
Mobile Safari: JavaScript Focus() Method on Inputfield Only Works with Click
<Iframe> JavaScript Access Parent Dom Across Domains
Method for Streaming Data from Browser to Server via Http
What's the Best Way to Loop Through a Set of Elements in JavaScript
What Is the Meaning of Symbol $ in Jquery
How to Highlight the Text of the Dom Range Object
JavaScript Change Date into Format of (Dd/Mm/Yyyy)
How to Set the Prototype of a JavaScript Object That Has Already Been Instantiated