How To Query Firebase Items With Specific Reference Type
I have a parent collection categories
and it child collection directories
Directories
connected with Categories
via Category
property
I want to query all directories with category equal to level
this.firestore
.collection<any>('directories', ref => ref.where('categories', '==', 'levels'))
.get()
.pipe(
map(x => {
const out: [] = [];
x.forEach(y => {
out.push(y.data());
});
return out;
})
);
I am getting an empty array in return. How would you fix that?
UPDATE based on the answer provided by @renaud-tarnec:
const categoryDocRef = this.firestore.doc('categories/levels');
this.firestore
.collection<any>('directories', ref => ref.where('categories', '==', categoryDocRef))
.get()
.pipe(
map(x => {
const out: [] = [];
x.forEach(y => {
out.push(y.data());
});
return out;
})
);
Now having an error core.js:15713 ERROR Error: Function Query.where() called with invalid data. Unsupported field value: a custom AngularFirestoreDocument object
Answer
If you want to use the DocumentReference data type in a query, you have to build a DocumentReference and use it in your query, as follows (in "standard" JavaScript):
const categoryDocRef = firebase.firestore().doc('categories/levels');
firebase.firestore().collection("directories").where("parent", "==", categoryDocRef)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
I've made the assumption that the documents containing the field parent
(which , in turn, contains the DocumentReference
type data) are in a collection named directories
.
UPDATE: It appears that the following won't work with angularFire2, see the comments
So, if I am not mistaking, this would be done as follow in angular, based on the code of your question:
const categoryDocRef = this.firestore.doc('categories/levels');
this.firestore
.collection<any>('directories', ref => ref.where('parent', '==', categoryDocRef))
.get()
...
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM