I am storing data based on dates in my real-time database. The dates range from today's date and a week forward. At certain points, I would like to loop through my real-time database and check if any dates in the database are now in the past, and if they are, delete them and their children.
I have an array of up-to-date dates, that I can use as reference by looping through all dates in my database and checking if it exists in my array. And my current solution looks like below, but gives me this error: TypeError: rootRef.once is not a function
.
function removeOldData() {
let rootRef = ref(db, "/");
rootRef.once("value")
.then(function(snapshot) {
snapshot.forEach(date => {
let ref = ref(db, `${date}/`);
if(!datesArr.includes(date)) {
remove(ref)
return;
}
})
});
}
I am new to firebase, and I am a bit confused about once()
's use. All suggestions on better/more efficient ways to do this are welcome. Thanks!
CodePudding user response:
You are using a combination of Firebase versions 8 and 9 syntax.
Depending on what version you are using you can do the following:
Version 8
function removeOldData() {
let rootRef = firebase.database().ref("/");
rootRef.once("value")
.then(function(snapshot) {
snapshot.forEach(date => {
let ref = ref(db, `${date}/`);
if(!datesArr.includes(date)) {
remove(ref)
return;
}
})
});
}
Version 9
function removeOldData() {
let rootRef = ref(db, "/");
onValue(ref(db, '/users/' userId), (snapshot) => {
snapshot.forEach(date => {
let ref = ref(db, `${date}/`);
if(!datesArr.includes(date)) {
remove(ref)
return;
}
})
}, {
onlyOnce: true
});
}
Docshttps://firebase.google.com/docs/database/web/read-and-write#read_data_once_with_an_observer
In some cases you may want the value from the local cache to be returned immediately, instead of checking for an updated value on the server.