javascriptfirebasegoogle-cloud-firestore

Getting the doc from the firestore isnt working as expected


Here is a pic of my firestore data. enter image description here

I am running this query:

var settings = [];
const queryGetSettings = db.collection('Settings').doc("Category");
var query = queryGetSettings.get()
    .then(snapshot3 => {

        snapshot3.forEach(doc => {
            settings.push({
                category: doc.data().CategorySettings
            })
        });

        res.json({
            "ack": "success",
            "settings": settings
        });

    })
    .catch(err => {
        res.json({
            'ack': "failure",
            'error': err,
            'API': "getSettingsUserChceck"
        });
    });

Its hitting the failure, but i also dont see any failure log in firebase console either. What is wrong with my get query?


Solution

  • Your queryGetSettings.get() is reading a single document from a known path, so the result is a DocumentSnapshot. The CategorySettings in the screenshot is an array field inside the CategorySettings document, but it itself not a collection or document.

    But your handler treats snapshot3 as if it's a query snapshot, which it isn't - so that part of your code will raise an error.

    Simple working code:

    const queryGetSettings = db.collection('Settings').doc("Category");
    var query = queryGetSettings.get()
        .then(doc => {
          console.log(doc.id, doc.data());
        });
    

    If you want to handle the values from the CategorySettings array field in a loop, you can do that with:

    let categorySettings = doc.data().CategorySettings;
    categorySettings.forEach((value) => {
      settings.push({
        category: value
      })  
    });