0

I have a collection named "users". I need to save 1 user and all data with this user.

const user= db.collection('users').where(firebase.firestore.FieldPath.documentId(), '==', presenceObj.data().UserId).get();

But does not receive the data.

console.log(user.data().name);

Doesn't write anything on console.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
FedFAr
  • 9
  • 5
  • The problem is typically not that the variable isn't saved, but that your `console.log(user.data().name)` runs before the data is loaded. See https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 for an explanation and how to deal with this. – Frank van Puffelen Jun 09 '21 at 14:54

1 Answers1

0

The problem is typically not that the variable isn't saved, but that your console.log(user.data().name) runs before the data is loaded.

See Why Does Firebase Lose Reference outside the once() Function? for an explanation and how to deal with this.

If you're running in a modern environment, you can use async and await to make the code a bit more readable:

const user= await db.collection('users')...;

But this is just syntactic sugar, and the data is still loaded asynchronously behind the scenes, so I highly recommend spending some time to read up on that.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807