to create document every 31 days from when cloud function action defined and only to the subcollection which i give reference with variable createpageA(in image).
in this i am creating new document in collection(Newvehicle)(its output variable is 'createpageA') simultaneously also in subcollection with reference createpageA then navigating to the page containing data of subcollection.
now what i want is, my backend firestore to create document every 31 days in subcollection with createpageA reference with fields i will chose.
i don't know coding much, i tried chatgpt to give me code and i used it but while test it says it did it but in firestore document was not created and in function dashboard also there was no request taken by firebase(for test i did that in duration of 1 minute)
can anyone give me code
this is the code i used:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code
exports.createPeriodicTransaction = functions.region('us-central1').https.onCall(
(data, context) => {
// Write your code below!
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.createPeriodicTransaction = functions.pubsub
.schedule('every 1 minutes')
.onRun(async (context) => {
try {
// Use the createpageA variable as the document reference
const createpageA = context.params.createpageA;
if (!createpageA) {
console.error('The variable createpageA is not provided.');
return null;
}
const db = admin.firestore();
// Reference the document in the Newvehicle collection
const docRef = db.collection('Newvehicle').doc(createpageA);
const docSnapshot = await docRef.get();
if (!docSnapshot.exists) {
console.error(`Document with ID ${createpageA} does not exist.`);
return null;
}
// Get the emi field value from the document
const docData = docSnapshot.data();
const emiValue = docData.emi;
if (!emiValue) {
console.error(`EMI field is missing for document ${createpageA}.`);
return null;
}
// Add a new document in the CustomertransactionN subcollection
await docRef.collection('CustomertransactionN').add({
date: admin.firestore.Timestamp.now(),
type: 'Due',
due_amount: emiValue,
});
console.log(`Transaction created successfully for document ${createpageA}.`);
return null;
} catch (error) {
console.error('Error creating transaction:', error);
throw new functions.https.HttpsError(
'internal',
'Failed to create transaction document.'
);
}
});
// Write your code above!
}
);