firebase Firestore:多个条件where子句

nom7f22z  于 2022-11-17  发布在  其他
关注(0)|答案(9)|浏览(118)

例如,我有一个动态的图书列表过滤器,我可以设置特定的颜色,作者和类别。

Book > Red, Blue > Adventure, Detective.

如何有条件地添加“where”?

firebase
    .firestore()
    .collection("book")
    .where("category", "==", )
    .where("color", "==", )
    .where("author", "==", )

    .orderBy("date")
    .get()
    .then(querySnapshot => {...
cczfrluj

cczfrluj1#

async yourFunction(){
    const Ref0 = firebase.firestore().collection("your_collection").doc(doc.id)

    const Ref1 = appointmentsRef.where('val1', '==',condition1).get();
    const Ref2 = appointmentsRef.where("val2", "!=", condition2).get()

    const [snapshot_val1, snapshot_val2] = await Promise.all([Ref1, Ref2]);

    
    const val1_Array = snapshot_val1.docs;
    const val2_Array = snapshot_val2.docs;

    const globale_val_Array = val1_Array .concat(val2_Array );

    return globale_val_Array ;
  }


/*Call you function*/
this.checkCurrentAppointment().then(docSnapshot=> {
      docSnapshot.forEach(doc=> {
          console.log("Your data with multiple code query:", doc.data());
      });
    });
ajsxfq5m

ajsxfq5m2#

由于CollectionRef在firebase web版本9中没有query方法,
我修改了@abk的回答。

async getQueryResult(path, options = {}) {
    /* Example
    options = {
      where: [
        ["isPublic", "==", true],
        ["isDeleted", "==", false]
      ],
      orderBy: [
        ["likes"],
        ["title", "desc"]
      ],
      limit: 30
    }
    */

    try {
      let { where, orderBy, limit } = options;

      let collectionRef = collection(<firestore>, path);
      let queryConstraints = [];

      if (where) {
        where = where.map((w) => firestore.where(...w));
        queryConstraints = [...queryConstraints, ...where];
      }

      if (orderBy) {
        orderBy = orderBy.map((o) => firestore.orderBy(...o));
        queryConstraints = [...queryConstraints, ...orderBy];
      }

      if (limit) {
        limit = firestore.limit(limit);
        queryConstraints = [...queryConstraints, limit];
      }

      const query = firestore.query(collectionRef, ...queryConstraints);
      const querySnapshot = await firestore.getDocs(query);
      const docList = querySnapshot.docs.map((doc) => {
        const data = doc.data();
        return {
          id: doc.id,
          ...data,
        };
      });
      return docList;
    } catch (error) {
      console.log(error);
    }
  }
xuo3flqw

xuo3flqw3#

正如您在API文档中所看到的,()方法返回一个CollectionReference。CollectionReference扩展Query,并且Query对象是不可变的。Query.where()和查询.orderBy()返回在原始Query之上添加操作的新Query对象您必须编写代码来记住这些新的Query对象,以便继续使用它们进行链调用。因此,您可以像这样重写代码:

var query = firebase.firestore().collection("book")
query = query.where(...)
query = query.where(...)
query = query.where(...)
query = query.orderBy(...)
query.get().then(...)

现在,您可以通过添加条件来确定在每个阶段要应用哪些过滤器,只需为每个新添加的过滤器重新分配query即可。

if (some_condition) {
    query = query.where(...)
}
8ftvxx2r

8ftvxx2r4#

Firebase版本9

这些文档没有涉及到这一点,但这里介绍了如何向查询添加条件where子句

import { collection, query, where } from 'firebase/firestore'

const queryConstraints = []
if (group != null) queryConstraints.push(where('group', '==', group))
if (pro != null) queryConstraints.push(where('pro', '==', pro))
const q = query(collection(db, 'videos'), ...queryConstraints)

这个答案的来源是我最好的朋友J-E^S^-U-S的一些直觉猜测和帮助

oxf4rvwz

oxf4rvwz5#

使用Firebase版本9(2022年1月更新):

您可以使用多个where子句筛选数据:

import { query, collection, where, getDocs } from "firebase/firestore";

const q = query(
  collection(db, "products"),
  where("category", "==", "Computer"),
  where("types", "array-contains", ['Laptop', 'Lenovo', 'Intel']),
  where("price", "<=", 1000),
);

const docsSnap = await getDocs(q);
    
docsSnap.forEach((doc) => {
  console.log(doc.data());
});
fkaflof6

fkaflof66#

除了@道格史蒂文森回答。当你有一个以上的where有必要使它更有活力,因为在我的情况。

function readDocuments(collection, options = {}) {
    let {where, orderBy, limit} = options;
    let query = firebase.firestore().collection(collection);

    if (where) {
        if (where[0] instanceof Array) {
            // It's an array of array
            for (let w of where) {
                query = query.where(...w);
            }
        } else {
            query = query.where(...where);
        }

    }

    if (orderBy) {
        query = query.orderBy(...orderBy);
    }

    if (limit) {
        query = query.limit(limit);
    }

    return query
            .get()
            .then()
            .catch()
    }

// Usage
// Multiple where
let options = {where: [["category", "==", "someCategory"], ["color", "==", "red"], ["author", "==", "Sam"]], orderBy: ["date", "desc"]};

//OR
// A single where
let options = {where: ["category", "==", "someCategory"]};

let documents = readDocuments("books", options);
iqih9akk

iqih9akk7#

请注意,多个WHERE子句本质上是AND操作。

lmvvr0a8

lmvvr0a88#

如果你使用的是angular fire,你可以这样使用reduce

const students = [studentID, studentID2,...];

this.afs.collection('classes',
  (ref: any) => students.reduce(
    (r: any, student: any) => r.where(`students.${student}`, '==', true)
    , ref)
).valueChanges({ idField: 'id' });

这是多个标记的示例...
您可以很容易地为任何非Angular 框架更改此设置。
对于OR查询(不能使用多个where子句),请参阅here

lg40wkob

lg40wkob9#

例如,有一个数组看起来像这样

const conditionList = [
  {
    key: 'anyField',
    operator: '==',
    value: 'any value',
  },
  {
    key: 'anyField',
    operator: '>',
    value: 'any value',
  },
  {
    key: 'anyField',
    operator: '<',
    value: 'any value',
  },
  {
    key: 'anyField',
    operator: '==',
    value: 'any value',
  },
  {
    key: 'anyField',
    operator: '==',
    value: 'any value',
  },
]

然后你可以把你想设置查询条件的集合放到这个函数中。

function* multipleWhere(
  collection,
  conditions = [{ field: '[doc].[field name]', operator: '==', value: '[any value]' }],
) {
  const pop = conditions.pop()
  if (pop) {
    yield* multipleWhere(
      collection.where(pop.key, pop.operator, pop.value),
      conditions,
    )
  }
  yield collection
}

您将会取得收集组查询的条件。

相关问题