Home > Software design >  Is there any way to combine range queries for different fields in cloud firestore?
Is there any way to combine range queries for different fields in cloud firestore?

Time:06-18

I know that the firestore does not support range queries on different fields (enter image description here

CodePudding user response:

Let me suggest a different data model to enable you run your query.

add a bool field called availableQuantityGreaterThan0.

Keep it updated using cloud functions. Then run your query like this:

db.collection("Inventory")
  .where("availableQuantityGreaterThan0", "==", true)
  .orderBy("discountPercentage", "desc").get();

Example cloud function to keep the field updated:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const db = admin.firestore();

exports.onUpdate = functions.firestore
  .document("/Inventory/{inventory_id}")
  .onUpdate((change, context) => {
    const params = context.params;
    const inventoryId = params.inventory_id;
    const inventory = change.after.data();
    const availableQuantityGreaterThan0 = inventory.availableQuantity > 0;

    return db.doc("/Inventory/"   inventoryId)
      .set({ availableQuantityGreaterThan0 }, { merge: true });
  });

Do this for onCreate also.

  • Related