Firebase Remove with Javascript

半腔热情 提交于 2021-01-29 17:24:42

问题


So I have this code:

firebase.database().ref('putninalog/'+ NadiiIndeksNaloga()).remove();

This removes etc. [0] and all data connected to that index in database (it doesn't matter which number exactly). When I remove that index how do I update all other indexes to start from 0.

Example:

[0] [1] [2] [3]

I remove: [0]

This stays:

[1] [2] [3]

I want this:

[0] [1] [2]

回答1:


There is no way to remove an item at an index and then update all subsequent indexes in one operation. You will have to:

  1. Read the entire parent node into your application code.
  2. Remove the item from the array in your application code.
  3. Write the entire array back to the database.

And if other users may be manipulating the array at the same time, you'll have to do this using a transaction to prevent the updates from conflicting with each other.

To find out more about a better way to deal with lists of data in Firebase, I recommend reading the documentation on appending items to a list of data and the blog post Best Practices: Arrays in Firebase.




回答2:


I did some digging, I cant do it the way I wanted. I realized it thanks to Frank's answer. I did it this way to find index of each item:

  ref.on('value',function(snap)
{
  snap.forEach(function(child)
{
  console.log(child.ref_.path.pieces_[1]); // This will return mentioned [index] from database

});
});


来源:https://stackoverflow.com/questions/65615178/firebase-remove-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!