只使用firebase的新记录 [英] only new records using firebase

查看:70
本文介绍了只使用firebase的新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Firebase获取邮件列表。问题是我只需要在打开页面后看到发送的消息。基本上我不需要将消息存储在数据库中,我只需要将消息广播到所有连接的设备。

I´m using Firebase to get a list of messages. The problem is that I only need to see messages sent after I opened the page. Basically I don´t need to store the messages in the database I just need to broadcast it to all connected devices.

ref.limitToLast(1).on('child_added', function(snapshot) {
    console.log(snapshot.name(), snapshot.val());
});

上面的代码正确地返回了最后一个孩子,但我在填充我的数据库时发送的消息我没有需要。什么时候删除旧消息?

The code above returns the last child correctly but I´m filling my database with messages I don´t need. When is the right time to delete "old" messages?

推荐答案

我不建议删除旧消息,而不是它使每个用户都只负责阅读新内容。

I don't recommend to delete the old messages, instead of it makes every user take care of reading only what is new.

如果您的数据结构有效,那么您只需要为模型添加1个属性。每次发送邮件时,都会在属性中添加时间戳。

If your data structure about the messages is working then you only need to add 1 attribute to your model. Each time a message is sent add the timestamp to it in an attribute.

以下是doc如何使用ServerValue.TIMESTAMP

现在每个消息节点都可以按时间戳排序。

Now every message node can be ordered by the timestamp.

"messages": {
    "chat_1": {
        "push_key_usually":{
         "message": "hello",
         "owner": "maybe the UID or the email",
         "chat_key": "chat_1",
         "key": "push_key_usually",
         "timestamp": 981212312
         }
    }
}

要完成此操作,您需要让每个用户在加载聊天时设置自己的时间戳。这样,您可以从数据库中获取该值,并使用该时间戳对您的消息进行排序。完整的顺序是首先查询值,如果它是null,那么这是第一次,只需使用自定义时间戳(可以是零或当前时间减去几分钟)询问每条消息或工作并设置值。如果它不为null,则将该值用于查询,并在获得后再次设置时间戳。

To complete this, you need to make every user set its own timestamp when they load the chat. This way you can fetch that value from the database and order your message using that timestamp. The complete order is to query the value first if it is null then is the first time, simply ask for every message or work using a custom timestamp (can be zero or current time minus some minutes) and set the value. If it is not null, then use that value for your query and after you get it, set the timestamp again.

"connections": {
    "user_UID": 12312412
}

现在你可以做类似这样的事情:

Now you can do something like this:

reference.child("messages/chat_1/push_key_usuarlly").orderByChild("timestamp").startAt(yourTimeStamp).once...

这篇关于只使用firebase的新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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