问题
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