实时数据库本质上是一个大型 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 格式错误,您可能会因输入错误而无意中删除所有数据。