javascript - Is it possible to rename a key in the Firebase Realtime Database? -
i wondering, there way update key value?
let´s use following data:
i using set() write data. now, want user edit booktitle
, needs change on both places. tried using update() can´t seem make work. can edit booktitle
in bookinfo
not on books
.
moving not option because erase bookdata
. tried writing using push() then, can´t search because don´t have pushid (i need search because users can't have 2 books same name)
so, there way update key value? or, there better approach this? accept suggestions. thank you!
update: i´m using update book title inside bookinfo
var bookname = document.getelementbyid('bookname').value; firebase.database().ref('books/' + bookname + '/bookinfo').update({ booktitle : bookname });
i think see you're trying do. firebase doesn't have concept of "renaming" part of path via update. instead have remove existing node , recreate it. can so:
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); });
this remove info books/oldtitle
, re-populate new title in books/newtitle
.
caveat: relies on reading data , performing second async update. if have multiple users operating on same data @ same time cause issues. use transaction atomically if /books
top-level resource many nodes may cause performance problems.
if 1 person edit data @ time, above solution fine. if not, may want consider using non-user-controlled identifier such push id.
Comments
Post a Comment