如何将文档添加到Firestore文档子集合

时间:2019-08-21 12:09:38

标签: firebase web google-cloud-firestore

我想将文档添加到文档的子集合中,但是它不起作用(代码执行在第一次等待时挂起)。该代码在带有Firebase 6.4.0的浏览器中运行。

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();

我尝试使用users/${uid}/lists表示路径,但这没有任何改变。

正确设置了Firestore规则:

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;
    }
  }
}

我可以使用用户文档上的中间get()使其工作,但我认为这没有必要:

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();

我在第一个代码段中做错了什么吗?

在此先感谢您的帮助;-)

编辑:就像我在评论中说的那样,这被redux-thunk占用,这是完整的方法实现:

export const createList = (
  title: string,
  description: string
): ThunkAction<void, AppState, null, CreateListActions> => async (
  dispatch,
  getState
) => {
  const { uid } = getState().auth.currentUser!;

  dispatch(createListStarted({ title, description }));

  try {
    const listReference = await firebase
      .firestore()
      .collection('users')
      .doc(uid)
      .collection('lists')
      .add({
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
        title,
        description
      });
    const listSnapshot = await listReference.get();
    const list = toObject<List>(listSnapshot);

    dispatch(createListSucceeded(list));
    history.push('/lists');
  } catch (error) {
    dispatch(createListFailed(error));
  }
};

1 个答案:

答案 0 :(得分:0)

这可能是Firebase软件包6.4.0版中的错误。我安装了6.3.5版本,问题消失了!

相关问题