Reputation: 15
I have a little problem. My database has this structure:
place2:
{
House1:
{
locker{
'7801',
{
keycode: '333333',
number: '7801'
},
'7802',
{
keycode: '123456',
number: '7802'
}
}
},
House2:
{
locker
{
'7901',
{
keycode: '444444',
number: '7901'
},
'7902',
{
keycode: '654987',
number: '7902'
}
}
}
}
I need to separate the data for each "House", but by my code, it returns me like this:
House1: [ '7801', {keycode: '333333', number: '7801'}]
House1: [ '7802', {keycode: '654987', number: '7802'}]
House2: [ '7901', {keycode: '444444', number: '7901'}]
House2: [ '7902', {keycode: '654987', number: '7902'}]
It would need to be returned as in the structure, like this:
House1: [ '7801', {keycode: '333333', number: '7801'}, '7802', {keycode: '654987', number: '7802'}]
House2: [ '7901', {keycode: '444444', number: '7901'}, '7902', {keycode: '654987', number: '7902'}]
But I don't know where I can be going wrong. This is my code:
console.log("Getting all places");
let results=[];
let documents = db.collection('place2').get()
.then(snapshot => {
snapshot.forEach(doc => {
var namePlace = doc.id;
let subCollectionDocs = db.collection('place2').doc(doc.id).collection("locker").get()
.then(snapshot => {
snapshot.forEach(doc => {
results = []
results.push(doc.id, doc.data());
console.log(namePlace+": ", results);
})
}).catch(err => {
console.log("Error getting sub-collection documents", err);
})
});
}).catch(err => {
console.log("Error getting documents", err);
});
Thank you!
Upvotes: 0
Views: 53
Reputation: 595
The way you're doing is querying the database for each document, this will probabily lead to a high cost at larger scales.
Why would you need a structure like this ?
House1: [ '7801', {keycode: '333333', number: '7801'}, '7802', {keycode: '654987', number: '7802'}]
You're mixing the array with IDs and objects ?
TIP: When you perform a GET from place2 you will already get all of it's children nodes. Why don't you just simply use array.map or foreach, instead of querying the DB for everynode?
REMEMBER: If you're using firebase, when you .get(), the entire document will be returned, so you already have the data, it's just a matter of manipulating docs and arrays.
TIP2: When using NoSQL you store data aiming to read it, so you should store data the way you would query it, without needing to perform for every read, these bunch of calculations.
Upvotes: 1