Search code examples
node.jsfirebase-realtime-databasegoogle-cloud-functionsfirebase-admin

firebase cloud function transaction Cannot set property


i have a cloud firebase function. I want to match users here. but when I want to update the new user list in transaction. Everything works fine until I get to the transaction. it just gives a problem in the update process I get an error. where did i go wrong?

 function EslesmeUser(userID, gameID, users, level) {
      this.userID = userID;
      this.gameID = gameID;
      this.users = users;
      this.level = level;
    }
    
    
exports.miniOyunEslemeOnline = functions.database.ref("/test/guncelle22/{player}")
.onCreate((eslesecekSnap, context) => {
  return database.ref().child("test").child("guncelle22").once("value").then((players) => {

    const eslesecek = new EslesmeUser(eslesecekSnap.key, eslesecekSnap.child("gameID").val(), eslesecekSnap.child("users").val(), eslesecekSnap.child("level").val());
    eslesecek.users[0] = "testuser1";

    database.ref().child("test").child("guncelle22").transaction(function (players) {    
        const NewValue = {
          gameID: eslesecek.gameID,
          level: eslesecek.level,   
          users: eslesecek.users,
        };
        players[eslesecek.userID] = NewValue; //---> ERROR İS HERE.
      return players;
    });

    return null;
  }).catch((error) => {
    console.log(error);
  });
});

error screen shot ( eslesecek.userID = usersid000)

error

my db model

db model


Solution

  • The first time it runs, your transaction handler will be called with null. Even if you know a value exists in the database, you'll need to deal with this null, and return what the data should become if no data exists.

    So something like this:

    database.ref().child("test").child("guncelle22").transaction(function (players) {
        if (players !== null) {
            const NewValue = {
              gameID: eslesecek.gameID,
              level: eslesecek.level,   
              users: eslesecek.users,
            };
            players[eslesecek.userID] = NewValue;
        }
        return players;
    });
    

    With the updated code:

    1. The first time your callback is run, it will get null and returns null to the database too.
    2. The database then notices that the data is actually not null, and your code executes again, but now with the correct value for players.