I am new to firebase cloud functions and I want to update username
field of some documents from posts
collection when the users
collection changes it username
field of a particular document.
I use the following code to do that:
exports.updateProfileUsername = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) =>
{
const {userId} = context.params;
var newUsername = change.after.data().username;
var previousUsername = change.before.data().username;
if (newUsername.localeCompare(previousUsername) !== 0)
{
let postCollectionRef = db.collection('posts');
let postQuery = postCollectionRef.where('userId', '==', `${userId}`);
return new Promise((resolve, reject) =>
{
updateUsernameDocuments(postQuery, reject, newUsername);
});
}
});
function updateUsernameDocuments(query, reject, newValue)
{
query.get()
.then((snapshot) =>
{
if (snapshot.size === 0)
{
return 0;
}
return snapshot.docs.forEach((doc) =>
{
doc.ref.update({username : `${newValue}`});
});
}).catch(reject);
}
This code works fine. usernames in posts
collection are changing correctly. But, after some time, the cloud functions log shows this log : Function execution took 60002 ms, finished with status: 'timeout'
. How to solve that?
And will this function be a problem if i have to update millions of docs in posts
collection?