Reputation: 3856
I couldn't figure what am I doing wrong so need an extra eye to figure out what am I doing wrong. I am trying out one the question's answer from Delete firebase data older than 2 hours which uses https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes and https://github.com/firebase/functions-samples/blob/master/delete-old-child-nodes/functions/index.js to delete a node after a time.
/root
/items
LoHgJSFt8hHi2o_hP: {
timestamp: 1497911193083,
...some_other_data
},
LoHgJSsGGHi2o_fD: {
timestamp: 1597911193083
...some_other_data
}
My index.js
looks like
//index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { createUser } = require('./auth/onCreate');
const { deleteOldData } = require('./auth/onDeleteOldData');
const serviceAccount = require('./ownerstown-admin.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://ownexxxxxxxx-c86cf.firebaseio.com'
});
exports.createUser = functions.firestore.document('users/{userId}').onCreate(createUser);
exports.deleteOldData = functions.database.ref('/referralIds/ids/{pushId}').onWrite(deleteOldData);
and then onDeleteOldData.js
// auth/onDeleteOldData.js
const CUT_OFF_TIME = 2 * 60 * 60 * 1000;
async function deleteOldData(change) {
console.log('starting nooowwwwwww');
const ref = change.after.ref.parent;
console.log('ref', ref);
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
console.log('snapshot', snapshot);
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
return ref.update(updates);
}
module.exports = {
deleteOldData
};
and pushing the data in a button click like
function createLoginId() {
const rootRef = Firebase.database.ref();
const allDetails = rootRef.child('referralIds/ids');
const timeStamp = Date.now();
const someId = uuidv4();
const { origin } = window.location;
const data = {
timeStamp,
someId,
createrId: id
};
const newRef = allDetails.push();
newRef.set(data);
}
But as soon as I push the data, it gets deleted in secs.
What am doing wrong?
Upvotes: 0
Views: 255
Reputation: 83153
The problem comes from the fact that when you write to the database you do
const timeStamp = Date.now();
//...
const data = {
timeStamp,
someId,
createrId: id
};
which means that you save a field timeStamp
, but your Cloud Function selects the node(s) to be deleted based on timestamp
(all in lower case).
Node names in the Realtime Database are case sensitive.
BTW, note that for the timestamp you could use
const timestamp = firebase.database.ServerValue.TIMESTAMP;
which is "a placeholder value for auto-populating the current timestamp as determined by the Firebase servers", see https://firebase.google.com/docs/reference/js/firebase.database.ServerValue
Upvotes: 1