Home > Software engineering >  I Want To Fetch Only data With A Specific Field Value On Firebase
I Want To Fetch Only data With A Specific Field Value On Firebase

Time:02-10

Here I have a collection of cars and bikes and don't want to fetch everything if users select they are looking for only Cars, there are 2 types of categories Vehicles and Motorcycles and in firestore I query them like:

[{category: vehicles, modelYear: 2008 }, {category: motorcycles, modelYear: 2012}]

but is there a way to query only the one the user has selected, Like:

    const [results, setResults] = useState([])

     useEffect(() => {
           if(vehicles === true){
            db.collection("automotive")
            .orderBy("category == Vehicles")
            .limit(5)
            .get()
            .then((collections) =>{
              const auto = collections.docs.map((res) => res.data())
              setResult(auto)
             })
           }
      }, [])

CodePudding user response:

Firebase Firestore have provided proper method to put condition on query and limit works only when you use orderby on field :

db.collection("automotive")
    .where("category == Vehicles")
    .orderBy("modelYear")
    .limit(5)
    .get()
    .then((collections) =>{
        const auto = collections.docs.map((res) => res.data())
        setResult(auto)
     });
  • Related