【问题标题】:Firebase how to read latest children node?Firebase how to read latest children node?
【发布时间】:2022-12-02 02:41:03
【问题描述】:

I'm new to firebase and currently I'm still trying to learn how to get the latest children node based in this RTDB. My nodeMCU will send new data periodically so I'm trying to get the latest node when its added and the value of that node. Can you provide with a sample code for me to understand better? And if possible please explain like I'm 5. Thank you and have a good day.

【问题讨论】:

    标签: node.js firebase-realtime-database google-cloud-functions arduino-esp32


    【解决方案1】:

    From what I understand you have an Arduino module that is going to be constantly introducing data into your database.

    What you want is to be able to read the value shown in the image asMQ7every time a new value is added.

    If this is the case there are different ways to obtain it.

    The first and most common one would be to use the firebaseChild Addedevent. With this event you can handle the data entered every time there is an addition to the reference to the database. Using this event you would have a set of all the values entered in your reference and with each addition automatically (In Real Time) this set would be updated.

    Taking your image as an example, the query code would be something like this (JS):

    dbRef.child("Sensor MQ7").on("child_added", (snap) => {
      for (i in snap.val()) {
        const value_MQ7 = snap.child(i).child("MQ7").val()
        // Do what you want with the value
        console.log(value_MQ7)
      }
    })
    

    If you don’t want to have that set with all the values entered in your reference, the best option would be a new function that returns only the value you are requesting, that is, a function that returns theMQ7value of the last object entered in your referencesensor MQ7.

    The query code would be something like this (JS):

    const query = dbRef.child("Sensor MQ7").orderByKey().limitToLast(1);
    
    query.get().then((snap) => {
      for (i in snap.val()) {
        // Do what you want with the value
        const value_MQ7 = snap.child(i).child("MQ7").val()
        console.log(value_MQ7)
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2022-12-26
      • 1970-01-01
      • 2011-04-06
      • 2022-12-19
      • 2022-12-02
      • 1970-01-01
      • 2022-12-26
      • 2022-12-27
      • 2020-09-27
      相关资源
      最近更新 更多