0

我在从 VueFire 更新 Firebase 时遇到了一些问题。我正在尝试使用以下方法,但如果我将任何字段留空(这应该在设置中经常发生),它会对我大喊大叫。知道为什么如果 .update 使用空白字段会生气吗?

错误:未捕获错误:Firebase.update 失败:第一个参数在属性“businesses.somebusiness.video”中包含未定义

updatePost(post) {
        postsRef.child(post['.key']).update({
          name: post.name,
          video: post.video,
          story: post.story,
          cover: post.cover,
          card: post.card
        })
      },

有一次,我将上面的内容重写为:

updatePost: function (post) {
        const businesschildKey = post['.key'];
        delete post['.key'];
        /* Set the updated post value */
        this.$firebaseRefs.posts.child(businesschildKey).set(post)
      },

它的效果非常好,但删除密钥似乎会导致 Vue 中出现奇怪的排序问题。如果我能找到一种方法在留空时不让它出错,我宁愿坚持使用顶级方法。

4

1 回答 1

2

根据这篇文章

When you pass an object to Firebase, the values of the properties can be a value or null (in which case the property will be removed). They can not be undefined, which is what you're passing in according to the error.

Your error message suggests that post.video's value is undefined. You can use logical-or to provide a fallback value like so:

  video: post.video || null,

That means whenever post.video has a false-y value, the expression will evaluate to null. That could catch empty string or numeric 0, though. To be more precisely correct, you should use

  video: typeof post.video === 'undefined' ? null : post.video,

If you need to do this check for many values, you can write a function for it:

function nullIfUndefined(value) {
  return typeof value === 'undefined' ? null : value;
}

then your expression would just be

  video: nullIfUndefined(post.video),
于 2017-04-14T20:45:33.150 回答