Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one generated key for chained push

Is there a way to let .push() || .push().key generate one key for chained .push()?

function saveItem(){
  const itemId = ref.push().key;
  let newItem = {id: itemId}

  ref.child(`items`)
      .push(newItem)
      .then(() => ref.child(`users/${uid}/items`)
      .push(itemId)
}

In example above I will generate 3 different keys instead of generating one even though there is itemId variable.

like image 284
nehel Avatar asked Apr 21 '26 23:04

nehel


1 Answers

Every push() call will create a new id. Chained push that is called three times will create three unique ids. So you need to use it only once to get unique id. Then if you want to write to a certain place(in your case to the 'items/id') you can use set() or update(). Set will overwrite all data at given location. While update will update only needed field at a lower level keys. Example below:

function saveItem(){
  let ref = firebase.database().ref();
  const itemId = ref.child('items').push().key;
  let newItem = {some: data}

  ref.child(`items/${itemId}`)
      .set(newItem)
      .then(() => {
         let updates = {};
         updates[`/items/${itemId}/someField`] = newData;
         ref.update(updates);
       });
}
like image 65
Yevgen Avatar answered Apr 23 '26 16:04

Yevgen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!