使Node.JS服务器实时更新FireBase数据库的最佳方法? [英] Best way to have a Node.JS server keep updated with a FireBase database in real time?

查看:35
本文介绍了使Node.JS服务器实时更新FireBase数据库的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个Node.JS服务器,可以在用户发出请求时从FireBase数据库读取和写入数据.

I currently have a Node.JS server set up that is able to read and write data from a FireBase database when a request is made from a user.

我想实现基于时间的事件,从而导致在某个日期或时间执行某项操作.不过,这里的关键是,我希望可以在几秒钟内自由执行此操作(例如,在30秒过后或13日(星期五)上午11:30之前向控制台写一条消息).

I would like to implement time based events that result in an action being performed at a certain date or time. The key thing here though, is that I want to have the freedom to do this in seconds (for example, write a message to console after 30 seconds have passed, or on Friday the 13th at 11:30am).

一种方法是将需要执行某项操作的日期/时间存储在数据库中,并每秒从数据库中读取一次,并将当前日期/时间与存储的事件进行比较,以便我们知道某项操作是否需要此时执行.就像您可以想象的那样,这将是对数据库的许多不必要的调用,并且确实感觉是实施此系统的一种糟糕方法.

A way to do this would be to store the date/time an action needs be performed in the database, and read from the database every second and compare the current date/time with events stored so we know if an action needs to be performed at this moment. As you can imagine though, this would be a lot of unnecessary calls to the database and really feels like a poor way to implement this system.

有没有一种方法可以与数据库保持同步而不必每秒调用一次?也许然后我可以在本地存储事件表的版本,并在对数据库进行更改时对其进行更新?那是一个更好的主意吗?我还有其他解决方案吗?

Is there a way I can stay synced with the database without having to call every second? Perhaps I could then store a version of the events table locally and update this when a change is made to the database? Would that be a better idea? Is there another solution I am missing?

任何建议将不胜感激,谢谢!

Any advice would be greatly appreciated, thanks!

我目前如何初始化数据库:

How I currently initialise the database:

firebase.initializeApp(firebaseConfig);
var database = firebase.database();

然后我如何从数据库中获取数据:

How I then get data from the database:

await database.ref('/').once('value', function(snapshot){
        snapshot.forEach(function(childSnapshot){
            if(childSnapshot.key === userName){
                userPreferences = childSnapshot.val().UserPreferences;
            }

        })
    });

推荐答案

Firebase once() API从数据库中读取一次数据,然后停止对其进行观察.

The Firebase once() API reads the data from the database once, and then stops observing it.

如果您改为使用 on() API,它将在获取初始值后继续观察数据库-并在数据库更改时调用您的代码.

If you instead us the on() API, it will continue observing the database after getting the initial value - and call your code whenever the database changes.

这篇关于使Node.JS服务器实时更新FireBase数据库的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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