sambit
sambit

Reputation: 133

How to retrieve child data in firebase with the key?

I am new in firebase . I want to fetch child data along with the key . The following code i have tried in nodejs Environment.

  var firebase = require("firebase");

    firebase.initializeApp({
       databaseURL: "https://some.firebaseio.com/"
    });


    var customer = firebase.database().ref().child('customer');

    const fname = "name";
    const lname = "title";
    customer.orderByChild("partnerFirstName").equalTo(fname).on('child_added', function (snapshot) {
       console.log(snapshot.val());

       var fn = snapshot.val().partnerFirstName;

       var custdata = snapshot.val();

       console.log(custdata);
       console.log("FirstName:"+fn);

       if (custdata.partnerFirstName === fn) {
         console.log(custdata);

       }


     });

The output is as follows

    {
      createdAt: '2018-03-20T23:25:35.212Z',
      partnerEmail: '[email protected]',
      partnerFirstName: 'name',
      partnerGender: 'male',
      partnerLastName: 'title',
      partnerPhone: '444-602-4444',
      profilePicture: 'assets/profile_icon.png',
      uid: 'x99wl8kkmJSENpNdVMXTXCh7amy2' }
      FirstName: name

In this case we are not getting the key value of the record but firstname is coming without any error .

But when we tried the following code the key is coming along with data but firstname is coming as undefined

 var customer = firebase.database().ref().child('customer');

        const fname = "Name";
        const lname = "Title";
        customer.orderByChild("partnerFirstName").equalTo(fname).on('value', function (snapshot) {
           console.log(snapshot.val());

           var fn = snapshot.val().partnerFirstName;

           var custdata = snapshot.val();

           console.log(custdata);
           console.log("FirstName:"+fn);
           if (custdata.partnerFirstName === fn) {
             console.log(custdata);

           }


         });

The output is as follows

{ '-L84iSPyr9bPvnJZ6BgV':
   { 
     createdAt: '2018-03-20T23:25:35.212Z',
     partnerEmail: '[email protected]',
     partnerFirstName: 'name',
     partnerGender: 'male',
     partnerLastName: 'title',
     partnerPhone: '444-602-4444',
     profilePicture: 'assets/profile_icon.png',
     uid: 'x99wl8kkmJSENpNdVMXTXCh7amy2' } }
     FirstName: undefined

How to get child data along with key?

Upvotes: 2

Views: 2295

Answers (3)

sambit
sambit

Reputation: 133

Thanks to all .I am successfully solved issues of this code .My main motive is to use above code to fetch json format through firebase cloud function.and it is working fine .I successfully searched firstname and lastname in the url and it fetched the corresponding record .

exports.getCustomerbyname2 = functions.https.onRequest((req, res) => {
    res.header('Content-Type', 'application/json');
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');


    if (req.method === 'OPTIONS') {
      res.status(204).send('');
    }
    const fname = req.query.fname;
    const lname = req.query.lname;

    var customer=admin.database().ref().child('customer'); 
    customer.on('child_added', function (snapshot) {
        var fname1 = snapshot.val().partnerFirstName; 
        var lname1 = snapshot.val().partnerLastName; 

       customer.orderByChild('partnerFirstName').equalTo(fname).once('value', function(snapshot) {


            var arr=[];
            if (fname1 === fname && lname1===lname) {
                arr.push(snapshot.val());
                console.log(snapshot.val());
                res.status(200).json({ customer: arr});


            }else{
                res.status(200).send('ERROR : ' + errorObject);

            }

        },function(errorObject){
            console.log("The read failed: " + errorObject.code);
           // res.status(200).send('ERROR : ' + errorObject);
        });

    });

});

Upvotes: 0

Chukwuemeka Ihedoro
Chukwuemeka Ihedoro

Reputation: 605

You should replace your code with

customer.orderByChild("partnerFirstName").equalTo(fname).on('value', 
    function (snapshot) {

       var snap = snapshot.val();
       var key = Object.keys(snap);
       var custdata = snap[key];
       var fn = snap[key].partnerFirstName;

       if (custdata.partnerFirstName === fn) {
         console.log(custdata);
       }
 });

to return both the key and the child

Upvotes: 2

Peter Haddad
Peter Haddad

Reputation: 80914

To get the key, try the following:

var ref = firebase.database().ref("customer").orderByChild("partnerFirstName").equalTo(fname);
ref.once("value").then(function(snapshot) {
snapshot.forEach(function(child){
var key = child.key; 
var partnerName=child.val().partnerFirstName;

  });
});

In the above, you iterate inside the children of customer and then retrieve the key using var key = child.key;

Upvotes: 2

Related Questions