query firebase for documents that contain an array of length > 0

被刻印的时光 ゝ 提交于 2020-04-13 23:32:55

问题


Is it possible to query firebase for documents in a collection where the number of elements in an array of a particular field is greater than 0

For my example, each document has-a field called 'people', which contains an array of integers (or the array is empty).

My search always return 0 documents, but I have documents that I can see when I search in the firestore database admin panel.

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
admin.initializeApp();

var db = admin.firestore();
export const helloWorld = functions.https.onRequest(function(req,res)
{
    var all_users = db.collection('users');
    var query = all_users.where("people.length", ">", 0).get().then(snapshot => 
    {
        let docs = snapshot.docs;

        //return 1st document found

        res.send(docs[0].data());
    });

    query.catch(error =>
    {
        res.status(500).send(error);
    });

});

回答1:


This is not possible with Firestore. The only things you can query for array type fields is the exact contents of some element in the array.

Your alternative for filtering on the size of any array is to use an integer field to record the number of elements in the array, and keep it in sync with changes to that array.




回答2:


It is possible with some sort of imagination and only if you know what would be inside of the array (NOT HOW MUCH, just the properties of the objects, or the type of primitive)

Lets say each people object will be {name:'...',age:'..'} A simple query would be:

firestore.collection('people').where('people.0.name','>','')

In case of primitives

firestore.collection('people').where('people.0','>','')

This way you will search for an array that has the first item name property not empty. If the array does not have a first property, then it's empty.

IMPORTANT: like i said, only works if you know what kind of object will be there



来源:https://stackoverflow.com/questions/55287819/query-firebase-for-documents-that-contain-an-array-of-length-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!