首页 > 解决方案 > TypeError: subcollection.push 不是函数

问题描述

我正在使用 Cloud Firestore 并制作评论部分,以便用户可以发表评论。

我在下面找到的一些代码:

 export function saveComment(comment, id, uid) {
     // database = firebase.database().ref('posts/');
     return dispatch => database.child(id).child('comments').push({ 
     content: comment.content, uid })
   }

上面的代码使用实时数据库,我不能使用 child() 作为 Cloud Firestore。

这是我的代码:

postActions.js

export const addComment = (postId, comment) => {
  return (dispatch, getState, { getFirebase, getFirestore }) => {
    const firestore = getFirestore();
    const firebase = getFirebase();
    const profile = getState().firebase.profile;
    const user = firebase.auth().currentUser;
    const ref = firestore.doc("posts/"+postId);
    const subcollection = ref.collection('comments')
    subcollection.push(comment)
  };
};

而不是 child(),我需要使用什么样的函数?在 Cloud Firestore 中

标签: javascriptreactjsgoogle-cloud-firestore

解决方案


push()您在使用 Cloud Firestore 时找到的方法来自 Firebase Realtime Database API。虽然这两个数据库都是 Firebase 的一部分,但它们是完全独立的,并且每个都有自己的 API。

要将新文档添加到 Cloud Firestore 集合,请使用addCollectionReference. 所以:

subcollection.add(comment)

有关添加文档,请参阅Firestore 文档


推荐阅读