Reputation: 701
I know that the firestore does not support range queries on different fields (as per the doc).
But I ran into a situation where I needed to check the quantity > 0 and order by discount percentage.
Like this
db.collection("Inventory").where("availableQuantity", ">", 0).orderBy("discountPercentage", "desc").get();
Can anyone help me with achieving this functionality? Or suggest me a different data model to store the data.
Upvotes: 0
Views: 162
Reputation: 2835
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.
Upvotes: 2