You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用setDoc()保存编辑内容至Firebase时遇类型错误求助

解决Firebase setDoc() 类型错误问题

问题详情

调用setDoc()时出现以下错误:

Uncaught FirebaseError: Expected type 'Ta2', but it was: a custom Aa2 object

相关代码如下:

模板部分

<div v-for="(post, id) in posts" :key="id">
  <h3>By: {{ post.name }}</h3>
  <p>{{ post.post }}</p>
  <p>{{ post.date }}</p>
    
  <button @click="deletePost(id)">delete</button>
      
  <div v-if="post === postItemToEdit">
    <input type="text" v-model="post.post" >
    <button @click="savePost">Save</button>
    <button @click="cancleEditMode">Cancle</button>
  </div>
      
  <button v-else @click="editPost(post)">Edit</button> 
</div>

脚本部分

<script setup>
  const blogCollectionRef = collection(db, "blogs")

  const name = ref("")
  const post = ref("")
    
  const addPost = () => {
    addDoc(blogCollectionRef, {
      name: name.value,
      post: post.value,
      date: Date.now(),
    });

    name.value = ""
    post.value = ""
  }

  const postItemToEdit = ref()

  const editPost = (post) => {
    postItemToEdit.value = post
  }
  
  const savePost = () => {
    postItemToEdit.value = (false)

    setDoc(blogCollectionRef, {
      post: "Los Angeles"
    })
  }
</script>

推测问题出在使用集合引用而非文档引用,但数据存储在名为“blogs”的集合中,该如何解决?


解决方案

  • 问题根源:setDoc() 要求第一个参数必须是文档引用,你现在传入的是集合引用(blogCollectionRef),这就导致了类型不匹配的错误。
  • 具体修正步骤:
    1. 保留文档ID:Vue的v-for里的id其实就是Firebase文档的ID(只要posts是直接从集合查询返回的结果),需要把这个ID传递给编辑和保存方法。
    2. 修改编辑状态存储:同时保存要编辑的帖子对象和对应的文档ID
      const postItemToEdit = ref({ post: null, docId: null })
      
      const editPost = (post, docId) => {
        postItemToEdit.value = { post, docId }
      }
      
    3. 更新模板调用:在v-for里传入文档ID,并修改editPost的调用参数
      <div v-for="(post, docId) in posts" :key="docId">
        <!-- 原有内容不变 -->
        <button v-else @click="editPost(post, docId)">Edit</button> 
      </div>
      
    4. 修正savePost方法:通过文档ID创建文档引用,再执行更新操作
      const savePost = () => {
        // 生成目标文档的引用
        const targetDocRef = doc(db, "blogs", postItemToEdit.value.docId)
        
        // 推荐用updateDoc更新指定字段,避免覆盖文档中其他未修改的内容
        updateDoc(targetDocRef, {
          post: postItemToEdit.value.post.post,
          date: Date.now() // 可选:添加修改时间戳
        })
        
        // 退出编辑状态
        postItemToEdit.value = { post: null, docId: null }
      }
      
  • 额外提示:
    • 如果一定要用setDoc(),它会完全覆盖整个文档,所以需要传入所有必要字段(比如name、date),防止原有数据丢失。
    • 取消编辑时,如果需要还原内容,可以在editPost时先保存原始数据,取消时恢复,避免修改后未保存的内容残留。

内容的提问来源于stack exchange,提问作者Mayana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:45:50