Can I rename a key in a Firebase Realtime database?

I was wondering if there is a way to update the key value?

Let's use the following data:

my data

I use set () to write data. Now I want the user to edit his own bookTitleand he must change in both places. I tried using update (), but I can't get it to work. I can edit bookTitlein bookInfoNOT on books.

Moving is not an option because it is bookData. I also tried writing using push (), but then I can’t search correctly because I don’t have pushID (I need a search because users cannot have two books with the same name)

So, is there a way to update the key value? or is there a better approach to this? I accept offers. Thank!

: , bookInfo

var bookName = document.getElementById('bookName').value;

firebase.database().ref('books/' + bookName + '/bookInfo').update({
    bookTitle : bookName
});
+14
5

, , . Firebase "" . node . :

var booksRef = firebase.database().ref('books');
booksRef.child(oldTitle).once('value').then(function(snap) {
  var data = snap.val();
  data.bookInfo.bookTitle = newTitle;
  var update = {};
  update[oldTitle] = null;
  update[newTitle] = data;
  return booksRef.update(update);
});

books/oldTitle books/newTitle.

:. . , , , , . transaction, , /books - , .

, . , - , push.

+19

JSON, , firebase / enter image description here

+1

, push().

var booksRef = firebaseRef.database().ref('books');
var newBookRef = booksRef.push(myBookData);
var bookKey = newBookRef.key;

: Firebase Docs - push()

, bookTitle ( ?), push(), remove(), set(), . - :

var bookRef = firebaseRef.database().ref('path/to/books/book1');

bookRef.on('value', function(snapshot) {
    var bookData = snapshot.val();
    var newData = {};
    var newTitle = 'NewTitle';

    bookData.bookInfo.bookTitle = newTitle;
    newData[newTitle] = bookData;
    firebaseRef.database().ref('path/to/books/' + newTitle).set(newData);

});
0

push(), - node firebase, . , ? , node , .

, ZenPylon, push() , , , .

0

, ...

, , (0) (1) , :

function mvFBkey(rtOrgn,rtDstn,rem){
  firebase.database().ref(rtOrgn).once('value').then(function(snap) {
    return firebase.database().ref(rtDstn).set(snap.val(),function(){
        if(rem)firebase.database().ref(rtOrgn).set(null);
    });
  });
}
0

Source: https://habr.com/ru/post/1652228/


All Articles