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)
my db model
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:
null
and returns null
to the database too.null
, and your code executes again, but now with the correct value for players
.