I'm adding documents to a subcollection called workReports
while I'm subscribed to it.
Method for query:
getWorkReportsByProjectId(projectId: string): Observable<ProjectWorkReport[]> {
return this.db
.collection("projects")
.doc(projectId)
.collection<ProjectWorkReport>(
"workReports",
ref => ref.where("invalid", "==", false).orderBy("createdAt", "desc")
)
.valueChanges({ idField: "id" });
}
Method for creating (notice createdAt
):
createProjectWorkReport(projectId: string, workReport: ProjectWorkReport): Promise<DocumentReference> {
return this.db
.collection("projects")
.doc(projectId)
.collection<ProjectWorkReport>("workReports")
.add({ ...workReport, createdAt: firebase.firestore.FieldValue.serverTimestamp() });
}
My subscription (I'm only loging the result):
this.projectsService.getWorkReportsByProjectId(projectId)
.pipe(takeUntil(this.destroyed$))
.subscribe((reports) => {
console.log(reports);
});
This is what's being logged. The element at position 0 is the new one because of orderBy("createdAt", "desc")
, but its createAt
property is null, but if make changes on the DB or make the query again, the new results have that createdAt
normally (and null
in the new one if I make another creation).
My guess is that Firestore takes the timestamp sentinel into account independently from the creation of the document, and the subscription fires before the timestamp is set.
Am I doing something wrong? And if my guess is right, what could I do as a fix?