Ruud
Ruud

Reputation: 65

Firebase - Update entry where value is

How do I get the Firebase unique id, so I can use it to reference a specific entry?

I am using the push method to store some data, each entry contains a weekNumber and year. I check if a weekNumber already exists, if so I need to update foo and bar. Checking if the weekNumber exists is no problem, but I can't figure out how to update the other fields.

Example data structure:

- ENTRIES
 - USER
  -JwphpyzzHaNlh8HXA2G
   foo: 'string'
   bar: 'string'
   weekNumber: 32
   year: 2015

  -Jwphpyzzaasd2H2DHB
   foo: 'string'
   bar: 'string'
   weekNumber: 33
   year: 2015

Checking if weekNumber exists:

ref.orderByChild('weekNumber').equalTo(data.weekNumber)
   .on('value', function(result) {

   });

I tried it with result.key() or result.parent(), but both return the path ENTRIES/USER and not the unique FB key.

Upvotes: 0

Views: 4896

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600071

With your current data structure, you can get the data with:

var query = ref.orderByChild('weekNumber').equalTo(data.weekNumber)
query.on('value', function(snapshot) {
    snapshot.forEach(function(weekSnapshot) {
        console.log(weekSnapshot.val());
        weekSnapshot.ref.update({ foo: 'newString' });
    });
});

But I would consider a different data structure.

Firebase's push() is great for collections where the items don't have a natural key, similar to how you'd put them in an array in JavaScript.

But in your case, the items have a natural key. It looks like you're trying to access items by year+week, which (from looking at the sample data) seems like a pretty unique identifier for a week in a year.

In that case, I would store the data under a year+week key as:

- ENTRIES
 - USER
  "201532"
   foo: 'string'
   bar: 'string'
   weekNumber: 32
   year: 2015

  "201533"
   foo: 'string'
   bar: 'string'
   weekNumber: 33
   year: 2015

With a structure like this, you can directly access a specific week/year:

ref.child('2015' + data.weekNumber).on('value', function(snapshot) {
    console.log(snapshot.val());
    snapshot.ref.update({ foo: 'newString' });
});

But you can also still query for year, with either of these:

// this will print all weeks of 2015
var query = ref.orderByKey().startAt('2015').endAt('201553');
query.on('child_added', function(snapshot) {
    console.log(snapshot.val());
});

Or even by a specific week in each year:

// this will print week 33 of each available year
var query = ref.orderByChild('weekNumber').equalTo('33');
query.on('child_added', function(snapshot) {
    console.log(snapshot.val());
});

Upvotes: 4

Related Questions