5

I'm currently manually itearting over document fields in firestore and putting them into an object which I stringify to JSON.

Is there a way to automate the process? Something like:

var userEnrollments = ToJson(await admin.firestore().collection(USERS + "/" + x.uid + "/" + ENROLMENT));
meds
  • 21,699
  • 37
  • 163
  • 314

2 Answers2

8

DocumentSnapshot has a method data() that returns the entire contents (without subcollections) of the document as a plain JavaScript object.

admin.firestore().doc('path/to/doc').get().then(snapshot => {
    const data = snapshot.data()  // a plain JS object 
})
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • unfortunately that doesn't seem to capture references. For example the enrolment document has a reference to a curriculum document but using snapshot.data() shows that as a documentreference rather than the plain JS object.. – meds Jan 02 '18 at 03:48
  • Right, that's how it works. All document reads in Firestore are shallow. You have to query again to get the next doc. https://stackoverflow.com/questions/46568850/what-is-firestore-reference-data-type-good-for – Doug Stevenson Jan 02 '18 at 04:06
  • That makes me very sad, I guess it would make more sense to store the IDs to those references to get deep copies working instead which kind of defeats the purpose of this whole thing.. – meds Jan 04 '18 at 12:51
  • https://stackoverflow.com/questions/46900906/whats-the-difference-between-using-a-documentreference-in-firestore-and-using-j https://stackoverflow.com/questions/46568850/what-is-firestore-reference-data-type-good-for/46570119 – Doug Stevenson Jan 04 '18 at 15:55
  • Alternatively: `const document = await firestore.collection("lol").doc("hi").get(); console.log(document.data());` – Boris Yakubchik Feb 16 '22 at 21:26
0

Try use observable

var userEnrollments = Observable<User>;
Document userDoc = this.db.doc<User>('User/'+id);
this.userEnrollments = this.userDoc.valueChanges();

You can use array like: Observable<User[]>; with FirestoreCollection<User>;

I use similar in angular fire. You can use ASYNC in firebase too.

Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68