簡體   English   中英

如何在firestore中存儲二叉樹節點

[英]How store binary tree nodes in firestore

我想在反應中創建一個二叉樹。我使用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 上,以便我可以檢索它並將其作為上述數組格式獲取?

您只需要傳遞封裝在對象中的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM