Hello, I have made Firebase function which is watching if users matched. All parts work, but i added one more method getUserDataById where i want to get extra data from users, it returns undefined. So this is what i tried:
exports.UserPressesLike = functions.database
.ref('/users/{userId}/matches/{otherUserId}')
.onCreate(async (snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
const userId = context.params.userId;
const matchedUserId = context.params.otherUserId;
const a = await checkUserMatch(userId, matchedUserId);
if (a === true) {
console.log('Its a match');
addNewChat(userId, matchedUserId);
//create chat for both users
} else {
console.log('There is no match');
//do nothing
console.log(a);
}
return null;
});
checkUserMatch = async (userId, matchedUserId) => {
const isLiked = await admin
.database()
.ref('/users/' + matchedUserId + '/matches/' + userId)
.once('value')
.then(snapshot => {
// let tempuserId = snapshot.val();
// if()
let isLiked = snapshot.exists();
console.log(isLiked);
return isLiked;
})
.catch(error => {
console.log(error);
return snapshot;
});
return isLiked;
};
addNewChat = async (userId, matchedUserId) => {
const user1 = await getUserDataById(userId);
const user2 = await getUserDataById(matchedUserId);
console.log(JSON.stringify('User data: ' + user1));
const snapshot = await admin
.database()
.ref('/chats')
.push({
members: { [userId]: true, [matchedUserId]: true },
[userId]: { username: [user1.username] },
[matchedUserId]: { username: [user2.username] },
});
};
getUserDataById = async userId => {
const snapshot = await admin
.database()
.ref('/users/' + userId)
.once('value')
.then(childsnapshot => {
let data = childsnapshot.val();
return data;
});
};
But I get error:
TypeError: Cannot read property 'username' of undefined
at addNewChat (/srv/index.js:93:36)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
The problem is in getUserDataById method. Because it returns undefined. Where I made mistake?
Why I get username: { 0 : emilis} it should be username: emilis??

