gpt4 book ai didi

javascript - 删除与某个子值关联的整个记录

转载 作者:行者123 更新时间:2023-12-02 21:45:53 25 4
gpt4 key购买 nike

我想使用输入的子值删除数据库中的整个记录这是我尝试过的代码

<body>

User Name:
<input type="text" name="user_name" id="user_name" placeholder="enter text"/><br><br>
Enter Email:
<input type="text" name="user_name" id="user_name2" placeholder="enter email" />

<br><br>


<input type="button" value="Save" onclick="save_user();" />
<input type="button" value="delete" onclick="delete_user();" />

<script>

var tblUsers = document.getElementById('tbl_users_list');
var databaseRef = firebase.database().ref('users/');
var rowIndex = 1;
var uid;
var childKey;
var childData;

databaseRef.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
childSnapshot.key;
childSnapshot.val();

var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
cellId.appendChild(document.createTextNode(childKey));
cellName.appendChild(document.createTextNode(childData.user_name));
cellName.appendChild(document.createTextNode(childData.user_name2));

rowIndex = rowIndex + 1;


});
});


function save_user(){
var user_name = document.getElementById('user_name').value;
var user_name2 = document.getElementById('user_name2').value;

uid = firebase.database().ref().child('users').push().key;

var data = {
user_id: uid,
user_name: user_name,
password: user_name2
}

var updates = {};
updates['/users/' + uid] = data;
firebase.database().ref().update(updates);

alert('The user is created successfully!');
reload_page();

document.writeln(uid);


}

function update_user(){
var user_name = document.getElementById('user_name').value;
var user_id = document.getElementById('user_id').value;

var data = {
user_id: user_id,
user_name: user_name
}

var updates = {};
updates['/users/' + user_id] = data;
firebase.database().ref().update(updates);

alert('The user is updated successfully!');

reload_page();
}

function delete_user(){
var user_id = document.getElementById('user_id').value;

firebase.database().ref().child('/users/' + user_id).remove();
alert('The user is deleted successfully!');
reload_page();
}

这里要引用和删除的子值是user_name2

我想要从这段代码中得到的只是删除与其关联的子值的记录

我的数据库看起来像 database reference

例如,我想删除与 child 姓名密码“ddd”关联的整个记录​​

最佳答案

Firebase 仅当知道该节点的完整、准确路径时才能写入该节点。如果您只知道节点的属性值,则首先需要执行查询来查找具有该值的节点,然后写入这些节点。

所以在你的情况下,会是这样的:

let password = "ddd"; // hard-coded value, but this could also be read from the HTML

let ref = firebase.database().ref("users");
let query = ref.orderByChild("password").equalTo(password);

query.once("value").then(function(results) {
results.forEach(function(snapshot) {
snapshot.ref.remove();
})
})

关于javascript - 删除与某个子值关联的整个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60252141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com