'array-contains' 查询不适用于引用的 Firestore [英] Firestore where 'array-contains' query doesn't work with references
问题描述
我有一个带有成员数组的聊天"集合,其中包含参与聊天的用户.问题是我想获得当前用户参与的所有聊天记录.
I have a collection 'chats' with a members array which contains users participating in the chat. The problem is I want to get all chats where the current user is participating.
我用这个查询来做到这一点:
I do this with this query:
getUserChats(): Observable<Chat[]> {
return this.auth.currUser
.pipe(
take(1),
switchMap(user => this.afs
.collection('chats', ref => ref.where('members', 'array-contains', `/users/${user.uid}`))
.snapshotChanges()
.pipe(
map(actions => {
return actions.map(action => {
const data = action.payload.doc.data() as Chat;
const id = action.payload.doc.id;
return {id, ...data};
});
})
) as Observable<Chat[]>
)
);
}
这适用于字符串,但不适用于引用.我怎样才能让它在参考文献上工作?
This works well for strings, but doesn't work with References. How can I also make it work on References?
绿色有效红色无效
绿色:字符串红色:参考
Green: String Red: Reference
推荐答案
@Alex Mamo 回答是对的,你需要一个 DocumentReference.
@Alex Mamo answer is right, you need a DocumentReference.
注意:您不能自己创建一个!
你必须通过查询 firebase 来获取引用!
You have to get the reference by querying firebase!
代码:
return this.auth.currUser
.pipe(
take(1),
switchMap(user => this.afs
.collection('chats', ref => ref.where('members', 'array-contains', this.afs
.collection('users')
.doc<User>(user.uid)
.ref))
.snapshotChanges()
.pipe(
map(actions => {
return actions.map(action => {
const data = action.payload.doc.data() as Chat;
const id = action.payload.doc.id;
return {id, ...data};
});
})
) as Observable<Chat[]>
)
);
关键部分是价值"部分,即:
The crucial part is the 'value' part which is:
this.afs
.collection('users')
.doc<User>(user.uid)
.ref
您查询并THEN获得带有 .ref 的引用!
You query and THEN get the reference with .ref!
就是这样!这就是您查询 DocumentReference 的方式!
That's it! That's how you query for a DocumentReference!
这篇关于'array-contains' 查询不适用于引用的 Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!