l2aelba
l2aelba

Reputation: 22147

Firebase push mutiple objects with keys

Im not sure how it calls, But I just want to push data like :

By using .push()

{
    '{this_should_be_a_key}' : {
        name : '',
        items : {
            '{this_should_be_a_key}' : {
                title : ''
            }
        }
    }
}

Now I do something like : should be good with promise

ref.push({
    'name' : ''
}).then(function(snapshot) {
    let key = snapshot.key;
    ref.child(key+'/items').push({
        title : ''
    });
}).catch(function(err) {
    console.log(err);
});

This I have to push 2 times, Any easier way to do or its possible to push just one time ? Like..

ref.push({
    'name' : '',
    'items' : {
        '{this_should_be_a_key}' {
            'title' : ''
        }
    }
}).then(function(snapshot) {
    alert('done');
}).catch(function(err) {
    console.log(err);
});

Upvotes: 0

Views: 123

Answers (2)

cartant
cartant

Reputation: 58400

Firebase's push keys are actually generated on the client and you can generate one by calling push with no arguments. It will return a Reference and its key will be the generated push key. This is entirely client-side and does not involve communicating with the server.

So you can generate a key, prepare your data and then call push again:

var key = ref.push().key;
var data = {
  name: '',
  items: {}
};
data.items[key] = { title: '' };

ref.push(data)
  .then(function () { console.log('pushed'); });
  .catch(function (error) { console.log(error); });

Upvotes: 1

Oussema Aroua
Oussema Aroua

Reputation: 5329

you can make a separate node for the items list and just save the key at the parent element

Upvotes: 0

Related Questions