繁体   English   中英

类型错误:doc 不是 addSubCollectionDocument 中的 function

[英]TypeError: doc is not a function at addSubCollectionDocument

我正在尝试将新文档添加到文档 (solutionsCollection/docID/commentsSubCollection) 中不存在的子集合中。 但是当我将文档添加到子集合时收到此错误消息:

类型错误:doc 不是 addSubCollectionDocument 中的 function

将新文档添加到comments子集合的代码:

  const addSubCollectionDocument = async (docID, doc) => {
    dispatch({ type: "IS_PENDING" })
    try {
      const docRef = doc(db, c, docID)
      const colRef = collection(docRef, "comments")
      const addedDocument = await addDoc(colRef, doc)
      dispatchIfNotCancelled({ type: "ADDED_DOCUMENT", payload: addedDocument })
      return addedDocument
    } catch (error) {
      console.log(error)
      dispatchIfNotCancelled({ type: "ERROR", payload: error })
      return null
    }
  }

handleSubmit function:

const handleSubmit = async (e) => {
    e.preventDefault()

    try {
      const commentToAdd = {
        id: Math.floor(Math.random() * 10000),
        content: newComment.trim(),
        reactions: [],
        user: {
          userID: user.uid,
          avatarURL: user.photoURL,
          displayName: user.displayName,
          username: user.reloadUserInfo.screenName,
        },
        replies: [],
        createdAt: new Date(),
      }
      await addSubCollectionDocument(id, commentToAdd)
      setNewComment("")
      if (response) {
        console.log(response.error)
      }
    } catch (error) {
      console.log(error)
    }
  }

使用Firestore钩子代码:

import { useEffect, useReducer, useState } from "react"
import {
  addDoc,
  collection,
  deleteDoc,
  doc,
  serverTimestamp,
  updateDoc,
} from "firebase/firestore"

import { db } from "../firebase/config"

export const useFirestore = (c) => {
  const [response, dispatch] = useReducer(firestoreReducer, initialState)
  const [isCancelled, setIsCancelled] = useState(false)

  // only dispatch is not cancelled
  const dispatchIfNotCancelled = (action) => {
    if (!isCancelled) {
      dispatch(action)
    }
  }

  // add a document
  const addDocument = async (doc) => {
    dispatch({ type: "IS_PENDING" })

    try {
      const createdAt = serverTimestamp()
      const addedDocument = await addDoc(collection(db, c), {
        ...doc,
        createdAt,
      })
      dispatchIfNotCancelled({ type: "ADDED_DOCUMENT", payload: addedDocument })
    } catch (err) {
      dispatchIfNotCancelled({ type: "ERROR", payload: err.message })
    }
  }

  // Add document to sub collection
  const addSubCollectionDocument = async (docID, doc) => {
    dispatch({ type: "IS_PENDING" })
    try {
      const docRef = doc(db, c, docID)
      const colRef = collection(docRef, "comments")
      const addedDocument = await addDoc(colRef, doc)
      dispatchIfNotCancelled({ type: "ADDED_DOCUMENT", payload: addedDocument })
      return addedDocument
    } catch (error) {
      console.log(error)
      dispatchIfNotCancelled({ type: "ERROR", payload: error })
      return null
    }
  }


  useEffect(() => {
    return () => setIsCancelled(true)
  }, [])

  return {
    addDocument,
    addSubCollectionDocument,
    response,
  }
}

我在其中导入addSubCollectionDocument挂钩的文件:

import { useFirestore } from "../../hooks/useFirestore"
import { useAuthContext } from "../../hooks/useAuthContext"

const SolutionComments = ({ solution }) => {
  const [newComment, setNewComment] = useState("")
  const { user } = useAuthContext()
  const { id } = useParams()
  const { addSubCollectionDocument, response } = useFirestore("solutions")

  const handleSubmit = async (e) => {
    e.preventDefault()

    try {
      const commentToAdd = {
        id: Math.floor(Math.random() * 10000),
        content: newComment.trim(),
        reactions: [],
        user: {
          userID: user.uid,
          avatarURL: user.photoURL,
          displayName: user.displayName,
          username: user.reloadUserInfo.screenName,
        },
        replies: [],
        createdAt: new Date(),
      }
      await addSubCollectionDocument(id, commentToAdd)
      setNewComment("")
      if (response) {
        console.log(response.error)
      }
    } catch (error) {
      console.log(error)
    }
  }

  return (...)}

Package.json 要点: https://gist.github.com/rishipurwar1/57fbf348cd9755a940e7e3f218de570f

Firebase规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
        match /challenges/{challenge}{
        allow read: if true
    }
    match /resources/{resource}{
        allow read: if true
    }
    match /solutions/{solution}{
      allow read: if true
      allow create: if request.auth.uid != null;
      allow update, delete: if request.auth.uid == resource.data.userID;
    }
    match /users/{userId}{
        allow create: if true
      allow read: if true
    }
  }
}
const addSubCollectionDocument = async (docID, doc) => { ... })
// That "doc" parameter is not a function      ^^^

该参数似乎是您传递给addSubCollectionDocument()的 object 。 尝试将其重命名为其他名称,例如:

const addSubCollectionDocument = async (docID, docData) => {
  const colRef = collection(db, c, docID, "comments")
  const addedDocument = await addDoc(colRef, doc)
})

您还没有为您的评论子集指定安全规则。 尝试添加以下规则:

match /c/{docId}/comments/{commentId} {
  allow read, write: if true; 
}

请根据您的用例将if true更新为所需的规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM