如何更新 Firebase 文档

How to Update Firebase document

当我尝试更新 Firebase 文档时,它在 console.

中显示 下面的错误消息

Unhandled promise rejection FirebaseError: "Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in field name)"

我尝试使用 console.log() 进行调试,但我发现在更新方法中无法识别变量 editedItem

如何解决这个问题

data: () => ({
    editedIndex: -1,
    editedItem: {
      id: 1,
      name: "SSFS",
      description: "XXXX"
    },
    newItem: {
      id: null,
      name: null,
      description: null
    }
  }),


    save() {
      if (this.editedIndex > -1) {
        // Update Category
        // Object.assign(this.desserts[this.editedIndex], this.editedItem);
        db.collection('categories').where('id', '==', this.editedItem.id).get().then( (querySnapshot) => {
          querySnapshot.forEach( (doc) => {
            doc.ref.update({
              name : this.editedItem.name,
              description : this.editedItem.description
            }).then(() => {
              this.$router.push('/categories') 
            })
          })
        })
      }
    }

错误:

Unhandled promise rejection FirebaseError: "Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in field name)

您试图以错误的方式访问数据对象。 您应该将数据函数更改为对象。

所以而不是:

data: () => ({
editedIndex: -1,
editedItem: {
  id: 1,
  name: "SSFS",
  description: "XXXX"
},
newItem: {
  id: null,
  name: null,
  description: null
}

}),

只需从此实现中删除函数,并将此数据作为常规对象呈现即可。

这样做:

data: {
editedIndex: -1,
editedItem: {
  id: 1,
  name: "SSFS",
  description: "XXXX"
},
newItem: {
  id: null,
  name: null,
  description: null
}

},

这将使您可以使用 'this' 关键字访问数据对象并获得正确的值。

现在您要做的就是更改这些行:

name : this.editedItem.name,
description : this.editedItem.description

进入这个:

name: this.data.editedItem.name,
description: this.data.editedItem.description