So I'm a newbie in using firebase real time database and I can't delete products key child with id specified.
I've tried this approach but it didn't yield any success:
removeProductById = async (id, user) => {
const userProductRef = db.ref(`products/product`);
try{
var query = userProductRef.orderByChild('id').equalTo(id);
query.remove()
})
}catch(error){
console.log(`The error has occured ${error.message}`)
}
}
So I wanna know how can one delete any tipe of key by whatever value they specify. Thank you in advance, you have always helped me guys.
CodePudding user response:
There are two problems here:
- Your query doesn't match the nodes you want delete.
- Firebase doesn't support delete-queries.
Your query doesn't match the nodes you want delete
Your query starts at a node products/product
, which doesn't exist in your database, and then orders/filters the id
property of each child node.
What you want instead is to start at the products
node, and then order/filter on its product/id
property of each child node:
In code:
const userProductRef = db.ref(`products`);
var query = userProductRef.orderByChild('product/id').equalTo(id);
Don't forget that you'll need to define an index for product/id
for this on the products
level in your rules.
Firebase doesn't support delete-queries
You can't simply pass the query and delete instruction to Firebase. To write a node in the database, you'll need to know the entire path to that node.
So you'll need to:
- Execute the a query.
- Loop over the results in your application code.
- Delete each matching node individually or in a multi-path update.
With the query
above, that'd be:
query.once("value").then((snapshot) => {
snapshot.forEach((child) => {
child.ref.remove();
});
})
Or with a multi-path/batch update:
query.once("value").then((snapshot) => {
let updates = {};
snapshot.forEach((child) => {
updates[child.key] = null;
});
ref.update(updates);
})