在Firestore中查询当前用户.once('value') [英] Query current user .once('value') in Firestore
问题描述
我正在将Firebase实时数据库转换为Firebase Firestore数据库,但是无法找到合适的引用来查询当前用户.
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();
}
});
最具体地说, once('value')
和 snapshot.val();
的替代品是什么?
Most specifically, what would be the replacement for once('value')
and snapshot.val();
?
我以为是
.onSnapshot(snapshot => {
const dbUser = snapshot.val();
...
推荐答案
Firestore中 once('value'
'的等效项称为 get()
,等效项的 val()
是 data()
.调用 get()
会返回一个承诺,所以:
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();
...
如果您有一个用户集合,则每个用户的个人资料都存储在以其UID作为ID的文档中,则可以使用以下命令加载该文件:
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();
请注意,有关获取数据的文档中已对此进行了很好的介绍.,因此我建议在那里花一些时间,并可能使用云Firestore代码实验室.
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.
这篇关于在Firestore中查询当前用户.once('value')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!