mercredi 21 août 2019

How to add a document to a firestore document subcollection

I'd like to add a document to a document's sub collection but it doesn't work (code execution hangs at the first await). The code is running in the browser.

const docRef = await firebase
  .firestore()
  .collection('users')
  .doc(uid)
  .collection('lists')
  .add({
    createdAt: firebase.firestore.FieldValue.serverTimestamp(),
    updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
    title,
    description
  });
const docSnapshot = await docRef.get();

I tried to express the path using users/${uid}/lists but this doesn't change anything.

The firestore rules are correctly set:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{document=**} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

I could make it work using and intermediary get on the user's document but I feel that's should not be necessary:

const userSnapshot = await firebase
  .firestore()
  .collection('users')
  .doc(uid)
  .get();
const docRef = await userSnapshot.ref.collection('lists').add({
  createdAt: firebase.firestore.FieldValue.serverTimestamp(),
  updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
  title,
  description
});
const docSnapshot = await docRef.get();

Am I doing something wrong in the first code snippet?

Thanks in advance for your help ;-)




Aucun commentaire:

Enregistrer un commentaire