简体   繁体   中英

Reading/writing nested data in a Firebase Database (web)

This seemingly simple question is surely a duplicate of many, so I apologize for that. Won't be offended when it's marked as such... But I have yet to find a clear, straight forward and modern answer that seems to work as I'd expect.

在此处输入图片说明

Given "Item One", how can I return the "subItems" array for the object that matches that title?

Additionally, how do I push new subitems to that array (if there's some different way I should target that array when writing rather than reading)

And the context of this is "items" is the top-level db.ref('items')

To find an item by a property, you need to run a query that orders and filters on that property. So in your case:

var ref = firebase.database().ref("items");
var query = ref.orderByChild("title").equalTo("Item One");
query.once("value", function(snapshot) {
  snapshot.forEach(function(item) {
    console.log(item.key); // -L8...EMj7P
    console.log(item.child("subItems").val()); // logs the sub items
    // console.log(item.ref.child("subItems").push().set(...)); // adds a sub item
  });
});

Note that nesting data types is an anti-pattern in the Firebase Database, since it typically leads to problems later on. A more idiomatic approach is to have two top-level lists (eg items and subItems ) that then use the same keys:

items: {
  -L8...EMj7P: {
    title: "Item One"
  }
},
subItems: {
  -L8...EMj7P: {
    ...
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM