DEV Community

Valentin Degenne
Valentin Degenne

Posted on • Updated on

Firestore

Firestore rules

  • If no rules are applied to a resource, no one can read/write in it.
  • Rules are applied to and only to the specified matched pattern and are not recursive. For instance allowing read access on /users/{uid} won't allow read access on /users/{uid}/documents/{docId}.
  • Only 1MB of data per document.

Accept access for everyone

match /path/to/resource {
  allow read: if true;
}
Enter fullscreen mode Exit fullscreen mode

Accept access if the user is connected

match /path/to/resource {
  allow read: if request.auth != null;
}
Enter fullscreen mode Exit fullscreen mode

Make a resource user-specific

match /user/{uid}/path/to/resource {
  allow read: if request.auth.uid == uid;
}
Enter fullscreen mode Exit fullscreen mode

Defining a function

function isAllowed(userId) {
  return request.auth.uid == userId;
}
match /user/{userId}/path/to/resource {
  allow read, write: if isAllowed(userId);
}
Enter fullscreen mode Exit fullscreen mode

JavaScript Web Modular SDK

  • addDoc: takes a collection and add the provided data, a document is appended to the collection with an auto-generated id.
  • setDoc: takes a document path (with custom id) and insert data, creates the document if it doesn't exist, if the document already exists the document is replaced (everything is replaced by the new data and data might be lost unless { merge: true } is used).
  • updateDoc: takes an existing document path (with custom id) and merge data, but if the document doesn't exist, the call throws an error.

onSnapshot

  • Can listen both on a document or a collection.
  • Callback on a document is called when information in the document changes but not if a collection is created/updated/removed inside of it (in fact a collection does not directly belong to a document.)
  • Callback on a collection is called when documents are added/updated/removed inside this collection but not if a collection is created/updated/removed inside one of the documents

arrayUnion

  • Doesn't work with setDoc and will replace all values.
  • Should be used with updateDoc.

Top comments (0)