如何在Firestore中存储二叉树节点

时间:2020-01-15 15:50:45

标签: javascript reactjs firebase google-cloud-firestore binary-tree

我想在react中创建一个二叉树。我正在使用 react-d3-tree 组件来显示树。 对于 react-d3-tree ,数据的格式应为

const myTreeData = [
  {
    name: 'Top Level',
    attributes: {
      keyA: 'val A',
      keyB: 'val B',
      keyC: 'val C',
    },
    children: [
      {
        name: 'Level 2: A',
        attributes: {
          keyA: 'val A',
          keyB: 'val B',
          keyC: 'val C',
        },
      },
      {
        name: 'Level 2: B',
      },
    ],
  },
];

如何在firestore上存储数据,以便我可以将其检索为上述数组格式?

1 个答案:

答案 0 :(得分:1)

您只需传递封装在对象中的myTreeData变量,如下所示:

const db = firebase.firestore();

const myTreeData = [
  {
    name: 'Top Level',
    attributes: {
      keyA: 'val A',
      keyB: 'val B',
      keyC: 'val C',
    },
    children: [
      {
        name: 'Level 2: A',
        attributes: {
          keyA: 'val A',
          keyB: 'val B',
          keyC: 'val C',
        },
      },
      {
        name: 'Level 2: B',
      },
    ],
  },
];

db.collection('yourCollection').add({tree: myTreeData})
.then(function(newDocRef) {
    return newDocRef.get();
}).then(function(doc) {
    console.log("JavaScript Object:", doc.data().tree);
    console.log("JSON:", JSON.stringify(doc.data().tree));
}).catch(function(error) {
    console.log("Error getting document:", error);
});

以上代码将{tree: myTreeData}对象保存在Firestore文档中并取回该文档,以便在控制台中记录tree字段的值(作为JavaScript对象和JSON)