我刚刚开始使用Firebase,并且正在尝试确定如何最好地构建我的Firestore数据库。
我想要的是从“事件”集合中找到所有文档,其中“参与者”(每个事件文档上的数组字段包含具有键'displayName'和'uid'的对象)包含至少一个匹配的uid。我正在比较的uid列表将是用户的朋友。
因此,在更多语义术语中,我想使用事件参与者和用户朋友的uid来查找该事件的至少一个参与者是“朋友”的所有事件。
希望我没有失去你。也许这个截图会有所帮助。
这样的深度查询是否可以与Firestore一起使用?或者我需要在客户端进行过滤吗?
编辑 - 添加代码
// TODO: filter events to only those containing friends
// first get current users friend list
firebase.firestore().doc(`users/${this.props.currentUser.uid}`)
.get()
.then(doc => {
return doc.data().friends
})
.then(friends => { // 'friends' is array of uid's here
// query events from firestore where participants contains first friend
// note: I plan on changing this design so that it checks participants array for ALL friends rather than just first index.
// but this is just a test to get it working...
firebase.firestore().collection("events").where("participants", "array-contains", friends[0])
.get()
.then(events => {
// this is giving me ALL events rather than
// filtering by friend uid which is what I'd expect
console.log(events)
// update state with updateEvents()
//this.props.dispatch(updateEvents(events))
})
})
我正在使用React-Native-Firebase
"react-native": "^0.55.0",
"react-native-firebase": "^4.3.8",
能够通过做@Neelavar所说的然后更改我的代码以便它在第一级集合查询中链接then()来解决这个问题。
// first get current users' friend list
firebase.firestore().doc(`users/${this.props.currentUser.uid}`)
.get()
.then(doc => {
return doc.data().friends
})
// then search the participants sub collection of the event
.then(friends => {
firebase.firestore().collection('events')
.get()
.then(eventsSnapshot => {
eventsSnapshot.forEach(doc => {
const { type, date, event_author, comment } = doc.data();
let event = {
doc,
id: doc.id,
type,
event_author,
participants: [],
date,
comment,
}
firebase.firestore().collection('events').doc(doc.id).collection('participants')
.get()
.then(participantsSnapshot => {
for(let i=0; i<participantsSnapshot.size;i++) {
if(participantsSnapshot.docs[i].exists) {
// if participant uid is in friends array, add event to events array
if(friends.includes(participantsSnapshot.docs[i].data().uid)) {
// add participant to event
let { displayName, uid } = participantsSnapshot.docs[i].data();
let participant = { displayName, uid }
event['participants'].push(participant)
events.push(event)
break;
}
}
}
})
.then(() => {
console.log(events)
this.props.dispatch(updateEvents(events))
})
.catch(e => {console.error(e)})
})
})
.catch(e => {console.error(e)})
})