Reputation: 1
I am trying to add a record in firestore database on everytime the cloud function is executed, But the function adds one record to the database only when the changed code is deployed and when the function is executed later, it doesnt add anything, Here is the code i am using, I dont know Node.js, using it for first time. Please help and point out what is wrong with the code and how it can be changed to add new row on each HTTP request to google cloud function.
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
let db = admin.firestore();
let FieldValue = require('firebase-admin').firestore.FieldValue;
let data = {
name: 'Los Angeles',
state: 'CA',
country: 'USA',
timestamp: FieldValue.serverTimestamp()
};
let result ="success";
(async () => {
// Add a new document in collection "cities" with ID 'LA'
let setDoc = await db.collection('cities').add(data).then((cityRef) => {
cityRef.get()
.then(doc => { result = "SUCC";/* do stuff */ })
.catch(err => { result = "FAI";/* error! */ });
});
})();
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!-' || result || setDoc;
res.status(200).send(message);
};
Upvotes: 0
Views: 74
Reputation: 317362
You have all your database code in the global scope of the function. That's not what you want at all. Try putting the code inside the Cloud Function trigger so that it executes when the function is invoked.
Upvotes: 1