如何在firebase中存储对象的顺序记录ID

时间:2014-09-24 06:20:15

标签: firebase

现在,当我将json对象推送到firebase时,它会自动创建记录的唯一ID,如下所示。

Groups
    -JXZDad3udDvZ076RD__
        GroupDescription:  Test
        GroupName:  test
        Id: 1
    -JXZK8AVfxp6RyNMTaLQ
        GroupDescription: Another test
        GroupName: Simple
        Id: 2

如何使它们(记录ID:-JXZDad3udDvZ076RD__)顺序如下。

 Groups 
    1
        GroupDescription:  Test
        GroupName:  test
        Id: 1
     2
        GroupDescription: Another test
        GroupName: Simple
        Id: 2

等待你的帮助。

2 个答案:

答案 0 :(得分:3)

现在,您可以使用以下内容将这些对象添加到Firebase:

var groups = [
  { GroupDescription: Test, GroupName: test, Id: 1 },
  { GroupDescription: Another test, GroupName: Simple, Id: 2 }
];
groups.forEach(function(group) {
  ref.push(group);
});

使用push告诉Firebase创建一个新子项并自动为您创建唯一的有序ID。

如果您想要控制新孩子的名字,您只需指定自己的child名称并使用set

groups.forEach(function(group) {
  ref.child(group.Id).set(group);
});

答案 1 :(得分:0)

您可以使用.then().push()之后由snapshot.key返回的承诺进行更新:

const ref = Firebase.database().ref(`/posts`);
ref.push({ title, categories, content, timestamp})
   .then((snapshot) => {
     ref.child(snapshot.key).update({"id": snapshot.key})
   });