bob_mosh
bob_mosh

Reputation: 335

How do I query a sub collection in EmberFire?

I am currently trying to fetch data from FireStore using EmberFire. Right now, my collection is /users and in there I store a user ID. Under the user ID I create another subcollecion, containing an array called /presets.

I want to use EmberFire to retrieve the presets for the currently logged in user. How can I tell this to EmberFire?

I tried fetching other data using EmberFire and it worked fine. For example, fetching documents from a collection works perfectly fine, I just have never used sub collections. Hence the question.

What I would like to achieve is something like

this.store.query('/users/pLvAT0TSbAjsnXoVmMF7yEG3mkW2/presets')

to get to the data stored in (collection users) -> (document pLvAT0TSbAjsnXoVmMF7yEG3mkW2) -> (collection presets).

Of course I would like to then use the traditional workflow to turn the documents in presets into views.

Right now, I am only able to work with a single collection. Nested collections are not something I am able to work with.

Does anyone have an idea on how to solve this?

Upvotes: 0

Views: 154

Answers (1)

user2716877
user2716877

Reputation: 63

A general answer would be:

this.store.find('users', 'pLvAT0TSbAjsnXoVmMF7yEG3mkW2').then((user)=>{
  return user.get('presets');
})

But it assumes some things done "the Ember way":

  1. There's User model
  2. There's a Preset model
  3. There's a hasMany relationship between User and Preset like this:
// app/models/user.js
import DS from 'ember-data';
const { Model, attr, hasMany } = DS;

export default Model.extend({
  presets: hasMany('preset', { subcollection: true })
});

Although the current version of Emberfire (v3-rc2) doesn't work pretty well with Subcollections, you'll be able to fetch records, but not create or update one.

Sources:

  • Emberfire guides (right now kind of empty, but hopefully someday it'll have good info)

Upvotes: 1

Related Questions