I'm having some trouble creating a new Document in my Firestore database using Cloud Functions. I am also using Postman to send a POST request with the following data:
{
"firstname": "TestFirst2",
"lastname": "TestLast2",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d2c3d5d294e6d2c3d5d288c5c9cb">[email protected]</a>"
}
This is the Cloud Function I am trying to run:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addUserReq = functions.https.onRequest((request, response) => {
const firstname = String(request.data.firstname)
const col = admin.firestore().collection(`users`)
col.add({
firstname: firstname,
lastname: request.data.lastname,
email: request.data.email})
.then(snapshot => {
const data = snapshot.data()
return response.send(data);
})
.catch(error => {
console.log(error)
response.status(500).send(error)
})
})
Here is the error message I am encountering:
TypeError: Cannot read property 'firstname' of undefined
at exports.addUserReq.functions.https.onRequest (/user_code/index.js:14:34)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
at /var/tmp/worker/worker.js:735:7
at /var/tmp/worker/worker.js:718:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
I have already checked the Firebase documentation, but couldn't find a solution. How can I prevent this error from occurring when trying to define the "firstname" parameter?
Update: This is a snippet of the index.js file in my web application that is encountering the same issue as the Postman request.
function save() {
var userFirstname = document.getElementById("firstname_field").value;
var userLastname = document.getElementById("lastname_field").value;
var userEmail = firebase.auth().currentUser.email_id;
var addUser = functions.httpsCallable('addUserReq');
addUser({
"users": {
"firstname": userFirstname,
"lastname": userLastname,
"email": userEmail
}
}
).then(function(result) {
var result = result;
}).catch((err) => {
alert(err)
});
}