Reputation: 3508
Is there a way to write -> read a newly added document in the firestore all in one go? I've been writing, then making a second query to read it, and while it works, I'm wondering if there is an alternate to what I have below. I've found similar questions here on SO, but a lot of them appear dated.
const someAsyncFunc = async () => {
try {
const lesson = await userLessonRef.get();
if (lesson.exists) {
// ? if lesson exists, return it.
return lesson.data();
}
// ? if lesson does NOT exist, create it.
await firebaseFirestore
.collection(`users/${userID}/languages/${language}/lessons`)
.doc(lessonID)
.set({ greetings: 'hello' });
// ? return the newly created lesson.
const newLesson = await firebaseFirestore
.collection(`users/${userID}/languages/${language}/lessons`)
.doc(lessonID)
.get();
return newLesson.data();
} catch (error) {
console.log('Error finding lesson collection', error);
}
}
Upvotes: 0
Views: 44
Reputation: 317740
Other than a transaction (which is a combined read-then-write operation, there are no combined write/read operations. If you need the entire contents of a document after writing it, then you will have to perform a read.
Upvotes: 2