In Firebase, is it possible to get data from the return of write function?

44 views Asked by At

I want to get user data from the return of creating a user, as below:

const newUserRes = await db.collection('users').add(userData);

Do you have any suggestions for me to get the new user document straight away from newUserRes?

I don't feel right to call a new read to get it:

const newUserRef = await db.collection('users').doc(newUserRes.id).get();

const newUser = newUserRef.data()
2

There are 2 answers

1
Frank van Puffelen On

The add() method returns an asynchronous DocumentReference, which does not contain a snapshot of the data that was just written. So you will indeed have to read the document after writing it, just a you do in your second snippet.

0
Thanh Nhật On

I found the solution to getting new user data directly from the write return (newUserRes)

const newUserSnapshot = await newUserRes.get();

const newUserData = newUserSnapshot.data();