I have document ids in a collection say idsCollection
. I have another collection where documents are actually stored say path-to-documents/docId
. I want an array say results
to return all documents. I'm trying to achieve this as follows:
function getAllDocuments(database: any) {
return new Promise((resolve, reject) => {
const idsCollection = "path/idsCollection"
const docPath = "path-to-documents/documents"
const dataSource = database
const dataRef = dataSource.collection(idsCollection);
const results = {};
dataRef.get()
.then(snapshot => {
snapshot.forEach(doc => {
let id = doc.data().docId
console.log("docId: " + id)
dataSource.doc(docPath+id).get()
.then(d => {
results[d.id] = d.data()
})
})
//return results[documentId]: {document}
if (Object.keys(results).length > 0) {
resolve(results);
} else {
resolve('No such document');
}
}).catch(err => {
reject(false);
console.log('Error getting documents', err);
});
})
}
Disclaimer: I'm new to NodeJs and Promise
.