【问题标题】:My firebase data disappears after some time一段时间后,我的 Firebase 数据消失了
【发布时间】:2021-03-19 23:50:44
【问题描述】:

我不擅长使用 firebase,但我成功地将我的数据库与我的代码集成在一起。它成功地将数据保存到实时数据库中,但是我注意到一段时间后数据就消失了,不知道为什么会这样。数据库不会永久存储数据是否有原因?

const handleSubmit = (e) => {
    e.preventDefault();
    
    const name = document.querySelector('#name').value
    const email = document.querySelector('#email').value
    const question = document.querySelector('#question').value

    const id = name + ' '+ email.slice(0,2)
    


    firebase.database().ref('table1/'+id).set({
      name: name,
      email: email,
      text:question,
    })
    
    success()
    setOpen(false);
    

  };

【问题讨论】:

  • 您也可以发布您的代码吗?
  • 当然!现在更新了
  • 您要么覆盖数据,要么尝试写入 nil 值(不小心),当这种情况发生时,节点就会消失。在实时数据库中,没有值的节点就无法存在。

标签: reactjs firebase firebase-realtime-database


【解决方案1】:

实时数据库本质上是一个大型 JSON 对象,将数据写入错误的位置可能会从数据库中删除数据。

首先要考虑的是如何将数据写入数据库。

使用您当前的代码,您将忽略写入数据库时​​收到的所有错误消息。这可能是丢失数据的原因之一。

使用Promise chaining处理错误:

/* ... */

firebase.database().ref('table1/'+id).set({
  name: name,
  email: email,
  text:question,
})
.then(
  () => {
    // data set successfully
    success();
    setOpen(false);
  },
  (err) => {
    // something went wrong
    // update UI with error info (missing data, needs login, etc)
    console.error(err);
  }
);

或更新的async/await syntax:

try {
  /* ... */

  await firebase.database().ref('table1/'+id).set({
    name: name,
    email: email,
    text:question,
  })

  // if here, data was set successfully
  success();
  setOpen(false);
} catch (error) {
  // if here, something went wrong
  // update UI with error info (missing data, needs login, etc)
  console.error(error);
}

另一个问题是将数据写入数据库的位置

想象一下下面的数据结构:

{
  table1: {
    pushId1: { /* ... */ },
    pushId2: { /* ... */ },
    pushId3: { /* ... */ },
    pushId4: { /* ... */ }
  },
  /* ... */
}

为简洁起见,我将省略如上所示的错误处理。您应该始终确保正确处理错误和承诺。

如果您将数据推送到table1,它会被添加到table1 中。

firebase.database().ref('table1').push({ /* ... */ });  // creates /table1/pushId5

如果您将数据设置为table1/<id>,它将作为子<id> 添加到table1 内。

firebase.database().ref('table1/' + id).set({ /* ... */ }); // creates/overwrites /table1/<id>
// or
firebase.database().ref('table1').child(id).set({ /* ... */ }); // creates/overwrites /table1/<id>

如果您改为将数据设置为table1,它会替换table1 内的所有数据

firebase.database().ref('table1').set({ /* ... */ }); // creates/overwrites /table1

这也会导致同样的结果:

firebase.database().ref('table1/').set({ /* ... */ }); // creates/overwrites /table1

使用您发布的代码,似乎没有任何输入验证。这可能会导致id = ' '.虽然' ' 的值本身不是问题,但如果你没有那个空间,比如id = name + email.slice(0,2),这意味着id 可能是''。在这种情况下,您的set() 操作将删除table1 中的所有值并将其替换为{ name, email, question } 对象。此外,如果您有其他类似“删除我的数据”的功能,但其 ID 格式错误,您可能会因输入错误而无意中删除所有数据。

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多