Query current user .once('value') in Firestore

淺唱寂寞╮ 提交于 2020-01-25 11:22:37

问题


I am transitioning a Firebase real-time database to a Firebase Firestore database but am having trouble finding the appropriate reference to query the current user.

onAuthUserListener = (next, fallback) =>
this.auth.onAuthStateChanged(authUser => {
  if (authUser) {
    this.user(authUser.uid)
      .once('value')
      .then(snapshot => {
        const dbUser = snapshot.val();

        // default empty roles
        if (!dbUser.roles) {
          dbUser.roles = [];
        }

        // merge auth and db user
        authUser = {
          uid: authUser.uid,
          email: authUser.email,
          emailVerified: authUser.emailVerified,
          providerData: authUser.providerData,
          ...dbUser,
        };

        next(authUser);
      });
  } else {
    fallback();
  }
});

Most specifically, what would be the replacement for once('value') and snapshot.val();?

I had thought that

.onSnapshot(snapshot => {
  const dbUser = snapshot.val();
  ...

回答1:


The equivalent of once('value' in Firestore is called get(), and the equivalent of val() is data(). Calling get() returns a promise, so:

.get().then(snapshot => {
  const dbUser = snapshot.data();
  ...

If you have a collection of users, where the profile of each user is stored within a document with their UID as its ID, you can load that with:

firebase.firestore().collection('users').doc(authUser.uid)
  .get()
  .then(snapshot => {
    const dbUser = snapshot.val();

Note that this is pretty well covered in the documentation on getting data, so I'd recommend spending some time there and potentially taking the Cloud Firestore codelab.



来源:https://stackoverflow.com/questions/53733232/query-current-user-oncevalue-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!