简体   繁体   中英

Unable to save data to Firestore using Google cloud function

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); };

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM