数据未添加到数据库中的现有节点 [英] Data is not added to existing node in database

查看:58
本文介绍了数据未添加到数据库中的现有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将数据添加到数据库中而没有任何运气.在我的代码中,单击时我创建了一个按钮,它将添加数据到我的用户数据库,但不会将其添加到用户,而只是将数据添加到外部,如下所示:

I have been trying to add data to my database without any luck. In my code i have made a button when click, it will add data to my users database but it will not add it to the user but it just add the data outside like this:

是因为使用createUserWithEmailAndPassword()函数后无法添加数据吗?

is it because you cant add data when you have use the createUserWithEmailAndPassword() function?

任何人都可以告诉我它是如何完成的吗?

Can anyone please show me how it is done?

btn.addEventListener("click", function()
{

    firebase.auth().onAuthStateChanged(function(user)
    { 
        if (user)
        {
            var massage = inputText.value;
            var ref = database.ref("Users");

            var data = {
                display: massage
            }
            ref.push(data);
        }
    });
});

推荐答案

无论何时调用 push(),Firebase都会生成一个新的唯一ID.因此,要将新数据添加到现有节点,不应调用push.相反,您需要找到对该用户的现有节点的引用.

Whenever you call push() Firebase generates a new unique ID. So to add the new data to the existing node, you should not call push. Instead you need to find a reference to the existing node for that user.

最简单(也是最常见)的方法是将用户数据存储在每个用户的UID下.

The easiest (and by far most common) way to do this, is to store the user data under the UID of each user.

Users
  kHD...NoS
    username: "bob"

还要注意,没有理由将这种类型的 onAuthStateChange 侦听器放在按钮单击处理程序中.只需从顶级JavaScript附加它,它就会在用户登录时或在其身份验证状态以任何其他方式更改时触发.

Also note that there's no reason to put this type of onAuthStateChange listener inside a button click handler. Just attach it from the top-level JavaScript and it will trigger whenever the user signs in or when their auth state changes in any other way.

或者,如果代码确实必须响应按钮单击而运行,则身份验证状态侦听器没有真正的用途,您只需检查 firebase.auth().currentUser :

Alternatively, if the code really must run in response to the button click, there's no real use for a auth state listener and you can just check firebase.auth().currentUser:

btn.addEventListener("click", function()
{
    if (firebase.auth().currentUser)
    {
        var message = inputText.value;
        var ref = database.ref("Users");

        var data = {
            display: massage
        }
        ref.child(firebase.auth().currentUser.uid).update(data);
    }
}

这篇关于数据未添加到数据库中的现有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆