Firebase - Update a record in which a value

How do I get a unique Firebase identifier, so I can use it to refer to a specific record?

I use the push method to store some data, each record contains the week number and year. I check if weekNumber already exists, if so I need to update foo and bar. Checking if weekNumber exists is not a problem, but I cannot figure out how to update 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 

Check for weekNumber:

 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 key FB.

0
source share
1 answer

With your current data structure, you can get data using:

 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 push() great for collections in which elements do not have a natural key, just like you put them in an array in JavaScript.

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

In this case, I will store the data for a year + week 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 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 request a year, with any of them:

 // 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()); }); 
+2
source

Source: https://habr.com/ru/post/1259364/


All Articles