How store binary tree nodes in firestore

本小妞迷上赌 提交于 2020-01-22 02:48:08

问题


I want to create a binary tree in react.I am using react-d3-tree component for displaying the tree. For react-d3-tree the data should be of the format

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',
      },
    ],
  },
];

How to store data on firestore so that I can retrieve it and get it as the above array format?


回答1:


You just have to pass your myTreeData variable encapsulated in an object, as follows:

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);
});

The above code saves the {tree: myTreeData} object in a Firestore document and gets back this document in order to log the value of the tree field in the console (as a JavaScript Object and as a JSON)



来源:https://stackoverflow.com/questions/59754992/how-store-binary-tree-nodes-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!