【问题标题】:Edit and Save data to firebase with setDoc()使用 setDoc() 编辑和保存数据到 firebase
【发布时间】:2022-11-02 23:47:57
【问题描述】:

Soo 我想将一个编辑过的项目从一个数组保存到 firebase 但是当我尝试使用 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>

我认为这与我使用集合而不是文档这一事实有关,但我正在获取的数组存储在我命名为“博客”的集合中。

【问题讨论】:

  • 您是否尝试添加具有随机 ID 的文档?如果是,请改用addDoc()。如果你想指定自己的ID,那么试试setDoc(doc(blogCollectionRef, "doc_id"))...
  • 我正在使用从 firebase 生成的 id,我不想添加另一个文档,我只想编辑并保存现有文档。
  • 感谢您的澄清。我看不到 posts 数组的来源,但请确保它包含文档 ID。

标签: javascript firebase google-cloud-firestore vuejs3


【解决方案1】:

您应该使用updateDoc() 来更新现有文档,而不是setDoc()。您将需要文档 ID,以便将其传递给 savePost() 函数:

<div v-for="(post, id) in posts" :key="id">
  <!-- ... -->
    <button @click="savePost(post.id)">Save</button>
  <!-- ... -->
</div>
const savePost = async (postId) => {
  postItemToEdit.value = (false)

  await updateDoc(doc(blogCollectionRef, postId), {
    post: "Los Angeles"
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2017-02-05
    • 1970-01-01
    • 2020-08-01
    • 2018-01-01
    相关资源
    最近更新 更多