0

I want to update an instance in realtime DB if the value exist
If in realtime DB have a same date with today, push the new data inside the resi
So each date have a lot of array inside the resi
I tried this thing, it created a new instance inside the db

firebase
        .database()
        .ref('resi-list')
        .orderByChild("date")
        .equalTo(moment().format('dddd, MMMM Do YYYY'))
        .once('value')
        .then(snapshot => {
          if (snapshot.val()) {
            firebase
              .database()
              .ref('resi-list')
              .child(snapshot.val().key)
              .update({
                resi: [{
                  noResi: resiForm.noResi,
                  type: resiForm.type,
                }]
              })
              .then(res => AlertInfo('Success', 'Success Post Data!', 'success'))
              .catch(err => AlertInfo('Oops', 'Error Post Data!', 'Error'));
          } else {
            firebase
              .database()
              .ref(`resi-list`)
              .push({
                date: moment().format('dddd, MMMM Do YYYY'),
                resi: [{
                  noResi: resiForm.noResi,
                  type: resiForm.type,
                }],
              })
              .then(res => {
                AlertInfo('Success...', 'Success Post Data', 'success');
                fetchResiList();
              })
              .catch(err => AlertInfo('Oops', 'Error Post Data', 'Error'));
          }
        }).catch(err => console.log(err));

DB Picture

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Miraii App
  • 81
  • 5

1 Answers1

0

If you want a certain value to be unique in the Realtime Database, you should use it as the key of a node. That is the only way to guarantee uniqueness.


So instead of storing your date as a property under the 0, use it as the key like this:

resi-list: {
  "2021-08-06": {
    resi: {
      ...
    }
  }
}

Now each data can only occur once under resi-list. In addition I changed your date format, to make sorting and filtering on it easier.


If you also want the noResi value to be unique under the resi of each date, you'd do the same there and use th noResi value as the key of those nodes:

resi-list: {
  "2021-08-06": {
    resi: {
      "EX102039-48576": {
        ...
      }
    }
  }
}

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807