0

I want to push data to firebase using nodejs. I have a string which contains value of MACID, I want to retrieve the key where MACID=macid(which is stored in firebase). And model(which is stored in firebase).

According to that I want to push data like' realdata={ temperature :"sasad", humidity : "123dsad4", timestamp :"dfssdsdf", }

firebase is like

enter image description here

As shown in image each user has many devices. I want to push data where macid=MACID. I have only MACID to compare.

How to push data to firebase where macid=MACID and it will store as seen in image.

Thanks in advance.

KENdi
  • 7,576
  • 2
  • 16
  • 31
Priya
  • 31
  • 6

2 Answers2

2

If you know the UID, you can query that user's devices for the one matching the MACID.

firebase.database().ref("users").child(uid).orderByChild("macid").equalTo(macId)

If you don't know the user's UID then the query is not possible with your current data structure. You will need to add an additional list that maps MACID to UID, e.g.

"macids": {
  "dasdad": "h1Eg5...."
  "dasasd": "h1Eg5...."
}

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2

If I understanding you correctly, you're looking to find a 'user' id (top-level) by querying a field that is nested two-deep (i.e. within the user object, then within the device object).

This is not possible with your database in its current format - see this question: Deep path query using wildcard as a path (in your instance, the 'wildcard' would be a device id).

I would reccommend you structure your database so you have lists of devices and users. For example:

users:
  -userId:
     -devices:
        -device ID:true,
        -device ID:true,
        -device ID:true
         etc....

devices:
  -deviceID:
     -users:
        -user ID:true,
        -user ID:true,
        -user ID:true
     -MACID: _____,
     -realData: _____,
     -etc...

*I'm never sure whether it's better to do [user ID]:[true], or [randomPushedId]:[user Id] - but both have the same effect. Maybe somebody could add to this.

You can then query your 'devices' node by MACID. Something like:

yourDatabaseRef.child("devices").orderByChild("MACID").equalTo([YOURMACIDHERE])
.once('value', (response) => { // GET KEY, THEN MAKE THE UPDATE })

In this instance, you're not actually using the 'users' node for anything - but I imagine you need it for something.

The most important thing is to think about how you're going to actually read your data, and then work out how your database should be structured from that. For example, if you're never going to get a list of devices by user, you won't need to add the devices references to the user node.

Goose
  • 190
  • 3
  • 12