skip to Main Content

I’m very new to Firebase cloud functions. Pardon me for my naive question.
I have a Firestore Database in this format :

Collection(Products) => Document(unknownId) => Collection(Cheap) => Document(Soap) => Fields

My question is how do I get the fields of Soap without knowing its complete path.
I have been fiddling around for last 2 days but no luck. I have tried many things but nothing seems to work, and I don’t know which code to share here since I tried so many. I read the firebase cloud functions docs but it’s more confusing.

exports.test = functions
  .https.onRequest((req, res) => {
      cors(req,res, async () => {
        admin.firestore().collectionGroup("Cheap").where(admin.firestore.FieldPath.documentId(), "==","Soap" ).get().then((result) => {
          console.log(result)
          res.status(200).send("Success") 
        }).catch((err) => {
          console.log('error')
        // }); 
      });
       
      })
});

3

Answers


  1. Chosen as BEST ANSWER

    I finally got an answer -

    exports.test = functions
    .https.onRequest((req, res) => {
        cors(req,res, async () => {
          let query = db.collectionGroup('Cheap')
          let response = []
          await query.get().then((data)=>{
            let docs = data.docs
            docs.map((val)=>{
              if (val.id == "Soap") {
                let Title = val.data().Title
                return response.push(Title)
              }
            })
          })
          return  res.status(200).send(response) 
          })
        })
    

    This worked for me, but this won't be an ideal solution if your database is huge. Hopefully that's not the case for me. Thanks ✨


  2. You can store the path you want to look for as a filed inside the document. In your case documentId(), "==","Soap", which is the relative path I’m assuming you need.

    Login or Signup to reply.
  3. The document ID field in a collection group query holds the entire path to the document, so your == on just the document name won’t work in this context.

    To allow the query, I’d probably store the value you want to query on in a field in the Cheap document too. So that means you’d give the Soap document a field Name: "Soap" too, and query on that field rather than the document ID.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search