I am trying to get the newly created firestore document id and use it in the same cloud function, but am getting some error!
Here is my cloud function:
exports.createNewGroup = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.HttpsError(
'unauthenticated',
'only autehnticated users can make requests!'
);
}
// Save a new group document and get the documents ID
const { id } = admin.firestore().collection('groups').set(data.group);
// Adding the group id to the groupmember object
data.groupMember.groupId = id;
// Save a new groupmember document with the newly created groupid added
admin.firestore().collection('groupMembers').set(data.groupMember);
return 'All is created perfectly';
});
When calling the function, I get this error in my functions log:
createNewGroup
Unhandled error TypeError: admin.firestore(...).collection(...).set is not a function
Not sure what I am doing wrong, and how to accomplish this?!?! Hoping for help and thanks in advance :-)
The set()
methods exists on a DocumentReference
but you are calling it on a CollectionReference
. If you are trying to add a document with random ID then use add()
method instead. Also both add()
and set()
return a promise so make sure you handle them:
exports.createNewGroup = functions.https.onCall(async (data, context) => {
// Async function ^^^^^
if (!context.auth) {
throw new functions.HttpsError(
'unauthenticated',
'only autehnticated users can make requests!'
);
}
const { id } = await admin.firestore().collection('groups').add(data.group);
// await it ^^^^^
// Adding the group id to the groupmember object
data.groupMember.groupId = id;
await admin.firestore().collection('groupMembers').add(data.groupMember);
return 'All is created perfectly';
});
Do note that .doc().set()
can also be used instead of .add()
. Both methods are equivalent.