[英]How can I delete some data from Firebase Realtime Database?
我有這個功能來保存和獲取數據:保存:
try {
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', {
method: 'post',
body: JSON.stringify(addNewLocation)
})
const response = await fetch(request)
window.location.reload()
return await response.json()
} catch (error) {
alert('Try again: ', error)
}
//to get:
try {
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'get'})
const response = await fetch(request)
return await response.json()
} catch (error) {
alert('Try again: ', error)
}
當我使用“刪除”而不是“獲取”時,它會完全刪除位置文件夾,但是當我使用鏈接末尾帶有鍵的鏈接時,我會收到錯誤消息
您可以使用刪除方法
let userRef = this.database.ref('users/' + userId);
userRef.remove()
您需要在需要刪除的位置發出DELETE
請求。
curl -X DELETE \
'https://[PROJECT_ID].firebaseio.com/locations.json'
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'DELETE'})
const response = await fetch(request)
return await response.json()
我不確定您的數據庫結構如何,但上述請求將刪除整個“位置”節點。 下面是一個例子:
如果您只想刪除location2
,請在https://[PROJECT_ID].firebaseio.com/locations/location2.json
發出刪除請求
我不確定您使用 REST API 是否有任何特定原因,但您可以嘗試使用 Firebase Web SDK 。 更容易使用,例如刪除location2:
firebase.database().ref("locations/location2").remove()
deleteSomeData(id) {
fetch(
// don't add .json at [data Name]
`https://[your FireBase project url]/[data Name (don't add .json)]/${id}.json`,
{
method: 'Delete',
headers: {
'Content-Type': 'application/json',
},
}
)
.then((response) => {
if (response.ok) {
// if sucess do something
} else {
// if fail throw error
throw new Error('could not delete data');
}
})
.catch((error) => {
this.error = error.message;
console.log(id);
});
},
您可以使用項目 ID 將其刪除,如下所示。
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations/<localtion_id>.json', { method: 'delete'})
您的位置 ID 可以是這樣的值,-MyB0qQoQuf9lPnwderfg
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.