'How can I get some firestore documents where one field has to be unique?
this function below should work, however I'm struggling to make it work.
I want to go to collection Listings and ensure that every listing is from a different Seller
The unique field is sellerID.
Here's the function:
export async function getUniqueHomeListings(amount: number) {
const listingsRef = collection(db, "listings");
let sellers = ["_"];
let dataArray = [];
[...Array(amount)].map(async () => {
console.log("SELLER IDS:", sellers);
let q = query(
listingsRef,
orderBy("sellerID", "desc"),
orderBy("date", "desc"),
where("status", "==", "listed"),
where("sellerID", "not-in", sellers),
limit(1)
);
const data = await getDocs(q);
let tempData = data.docs[0].data() as ListingObject;
if (!tempData) {
return;
}
tempData.docID = data.docs[0].id;
dataArray.push(tempData);
sellers.push(tempData.sellerID);
});
return {
listings: dataArray,
success: true,
};
}
So basically I want to give an a function an amount and it will give me back that amount of listings from unique sellers, or as many as it can in relation to the amount param.
The problem is, when console logging the sellers array inside the .map() function, it only contains the "_", not the seller ID's, therefore the where("sellerID", "not-in", sellers) doesn't work and gives me back listings from duplicate sellers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
