简体   繁体   中英

Accessing Firebase data in a node with JS

So I have an object being returned from Firebase that looks like this:

{key: {name: "test", email: "test", id: "test"}}

How can I get the id out of this object?

If I do returnItem I get that object, so I tried to do returnItem[0] but it's not an array, and I've tried (Object.keys(tempSnap) but that just gives me the key not the object inside it.

This is my current code:

export function sendInvitation(email) {
    firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
        let tempSnap = snapshot.val();
        if(tempSnap != null) {
            console.log(tempSnap);
        }
    });
    return dispatch => firebaseRef.database().ref(`${userID}/invites`).push("This is a test Message!"); 
}

This is what it outputs:

返回值

Help would be awesome :D

If you already know id and it's a literal, then it's a matter of returnItem.id .

If you already know id and it's a variable, then it's returnItem[id] .

If you don't know the keys and want to print all keys and their values, it's:

Object.keys(returnItem).forEach(function(key) {
  console.log(key, returnItem[key]);
});

Update

Your new code shows the problem. When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. Your callback needs to handle the fact that it gets a list by looping over the results with snapshot.forEach() :

firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
  snapshot.forEach(function(child) {
    let tempSnap = child.val();
    console.log(tempSnap);
  });
});

Try this:

firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
snapshot.forEach(function(child) {
    let keys=child.key;
    let ids=child.val().id;
      )};
   )};

you have:

 users
  keyid
   email:email
   name:yourname
   id: test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM