javascript - 如何在firestore中存储二叉树节点
问题描述
我想在 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上存储数据,以便我可以检索它并将其作为上述数组格式获取?
解决方案
您只需传递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)