Firestore: Query documents by property of object

2019-05-26 06:53发布

I've a collection with contacts with a structure like:

name: 'XPTO Company',
emails: { 
    susan@xpto.com: { name: 'Susan', text: 'manager' },
    fred@xpto.com: { name: 'Fred', text: 'marketing' }
}

How do I retrieve documents with email 'susan@xpto.com'

Something like:

firebase.firestore().collection('contacts')
      .where(new firebase.firestore.FieldPath('emails', email), '==', true).get()
      .then(snap => {
      })

1条回答
祖国的老花朵
2楼-- · 2019-05-26 07:40

You may add a property id that holds the email address to your email object. and replace '.' in email object key with '-', e.g. susan@xpto-com, so that your data structure look like this:

name: 'XPTO Company',
emails: { 
    susan@xpto-com: { id: 'susan@xpto.com', name: 'Susan', text: 'manager' },
    fred@xpto-com: { id: 'fred@xpto.com', name: 'Fred', text: 'marketing' }

Then you can retrieve documents with email 'susan@xpto.com' in this way:

firebase.firestore().collection('contacts')
      .where('emails.susan@xpto-com.id', '==', 'susan@xpto.com').get()
      .then(snap => {
      })
查看更多
登录 后发表回答