本文介绍了是否可以重命名 Firebase 实时数据库中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,有没有办法更新键值?

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

让我们使用以下数据:

我正在使用 set() 写入数据.现在,我希望用户编辑他们的 bookTitle 并且需要在两个地方进行更改.我尝试使用 update() 但我似乎无法让它工作.我只能编辑 bookInfo 中的 bookTitle 而不是 books.

I am using set() to write the data.Now, I want the user to edit their bookTitle and it needs to change on both places. I tried using update() but I can´t seem to make it work. I can only edit the bookTitle in bookInfo NOT on books.

移动不是一种选择,因为它会删除 bookData.我也尝试使用 push() 进行写作,但后来我无法正确搜索,因为我没有 pushID(我需要搜索,因为用户不能拥有两本同名的书)

Moving is not an option because it will erase the bookData.I also tried writing using push() but then, I can´t search properly because I don´t have the pushID (I need the search because users can't 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 suggestions. Thank you!

更新: 这是我目前用来更新 bookInfo

Update: This is what I´m currently using to update the book title inside bookInfo

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

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

推荐答案

我想我明白你想做什么了.Firebase 没有通过更新重命名"路径的一部分的概念.相反,您必须完全删除现有节点并重新创建它.你可以这样做:

I think I see what you're trying to do. Firebase doesn't have the concept of "renaming" a part of the path via update. Instead you will have to completely remove the existing node and recreate it. You can do that like 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);
});

这将从 books/oldTitle 中删除信息,并在 books/newTitle 中用新标题重新填充它.

This will remove the info from books/oldTitle and re-populate it with a new title in books/newTitle.

警告:这依赖于读取数据,然后执行第二次异步更新.如果您可能有多个用户同时操作相同的数据,这可能会导致问题.您可以使用 事务 以原子方式执行此操作,但如果/books 是顶级资源,节点多,可能会导致性能问题.

Caveat: This relies on reading the data and then performing a second async update. If you are likely to have multiple users operating on the same data at the same time this could cause issues. You could use a transaction to do this atomically but if /books is a top-level resource with many nodes that may cause performance problems.

如果一个人可能一次编辑数据,上面的解决方案就可以了.如果没有,您可能需要考虑使用非用户控制的标识符,例如推送 ID.

If one person is likely to edit the data at a time, the above solution is fine. If not, you may want to consider using a non-user-controlled identifier such as a push id.

这篇关于是否可以重命名 Firebase 实时数据库中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:34