如何从firebase实时数据库中删除一些数据?

z31licg0  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(452)

我有以下功能来保存和获取数据:保存:

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)
    }

当我使用“delete”而不是“get”时,它会完全删除locations文件夹,但是当我使用链接末尾带有键的链接时,我会得到一个错误

7z5jn7bk

7z5jn7bk1#

您可以使用remove方法

let userRef = this.database.ref('users/' + userId);
    userRef.remove()
iqih9akk

iqih9akk2#

你需要做一个决定 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 我不确定您使用RESTAPI是否有任何具体原因,但您可以尝试使用firebase web sdk。它更易于使用,例如删除位置2:

firebase.database().ref("locations/location2").remove()

相关问题