Firebase cloud function not updating record

1k Views Asked by At

imagine this scenario:

You have a list with lets say 100 items, a user favorites 12 items from the list.

The user now wants these 12 items displayed in a new list with the up to date data (if data changes from the original list/node)

What would be the best way to accomplish this without having to denormalize all of the data for each item?

is there a way to orderByChild().equalTo(multiple items)

(the multiple items being the favorited items)

Currently, I am successfully displaying the favorites in a new list but I am pushing all the data to the users node with the favorites, problem is when i change data, their data from favorites wont change.

note - these changes are made manually in the db and cannot be changed by the user (meta data that can potentially change)


UPDATE

I'm trying to achieve this now with cloud functions. I am trying to update the item but I can't seem to get it working.

Here is my code:

exports.itemUpdate = functions.database
  .ref('/items/{itemId}')
  .onUpdate((change, context) => {

  const before = change.before.val();  // DataSnapshot after the change
  const after = change.after.val();  // DataSnapshot after the change

  console.log(after);

  if (before.effects === after.effects) {
    console.log('effects didnt change')
    return null;
  }
   const ref = admin.database().ref('users')
   .orderByChild('likedItems')
   .equalTo(before.title);

   return ref.update(after);
});

I'm not to sure what I am doing wrong here.

Cheers!

1

There are 1 best solutions below

8
On

There isn't a way to do multiple items in the orderByChild, denormalising in NoSQL is fine its just about keeping it in sync like you mention. I would recommend using a Cloud Function which will help you to keep things in sync.

Another option is to use Firestore instead of the Realtime Database as it has better querying capabilities where you could store a users id in the document and using an array contains filter you could get all the users posts.

The below is the start of a Cloud function for a realtime database trigger for an update of an item.

exports.itemUpdate = functions.database.ref('/items/{itemId}')
    .onUpdate((snap, context) => {
        // Query your users node for matching items and update them
    });