Igniter
Igniter

Reputation: 887

Firebase DB updating and pushing simultaneously

Is there any way to update and push simultaneously?

I want to update a key2 in my object and simultaneously push unique keys under timeline in a single request ref().child('object').update({...}).

object
  key1:
  key2: // update
  key3:
  timeline:
    -LNIkVNlJDO75Bv4: // push
    ...

Is it even possible or one ought to make two calls in such cases?

Upvotes: 1

Views: 319

Answers (1)

Grimthorr
Grimthorr

Reputation: 6926

Calling push() with no arguments will return immediately (without saving to the database), providing you with a unique Reference. This gives you the opportunity to create unique keys without accessing the database.

As an example, to obtain a unique push key, you can do some something like:

var timelineRef = firebase.database().ref('object/timeline');
var newTimelineRef = timelineRef.push();
var newTimelineKey = newTimelineRef.key;

With this, you can then perform a multi-level update which makes use of the new key:

var objectRef = firebase.database().ref('object');

var updateData = {};
updateData['object/key2'] = { key: 'value' };
updateData['object/timeline/' + newTimelineKey] = { key: 'value' };

objectRef.update(updateData, function(error) {
  if (!error) {
    console.log('Data updated');
  }
});

Upvotes: 2

Related Questions