'Firebase database collection returns empty array when trying to get all documents

I'm trying to get all documents from my database collection "posts" but I'm getting an empty array instead.

The strange thing is that I'm able to get all documents from another collection called "users" that has the same structure and using the exact same code.

I've spent days looking for an answer but I haven't been able to find the solution.

This is the request:

const db = admin.firestore();

exports.getAllPosts = (req, res) => {

 db.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {  
   let posts = [];
   snapshot.forEach((doc) => {
     posts.push({
       id: doc.id,
       body: doc.data().body,
       author: doc.data().author,
       createdAt: doc.data().timestamp,
       voteScore: doc.data().voteScore
     });
   });
  return res.json(posts);
})
.catch(err => {
  console.error(err);
  res.status(500).json({ error: err.code });
});
}

And this is the response:

[]

This is what my current collection looks like: Posts collection screenshot

This the response that I get when I return "snapshot":

{
"_query": {
    "_firestore": {
        "_settings": {
            "projectId": "readable-bf7a6",
            "firebaseVersion": "9.6.0",
            "libName": "gccl",
            "libVersion": "4.10.0 fire/9.6.0"
        },
        "_settingsFrozen": true,
        "_serializer": {
            "allowUndefined": false
        },
        "_projectId": "readable-bf7a6",
        "registeredListenersCount": 0,
        "bulkWritersCount": 0,
        "_backoffSettings": {
            "initialDelayMs": 100,
            "maxDelayMs": 60000,
            "backoffFactor": 1.3
        },
        "_clientPool": {
            "concurrentOperationLimit": 100,
            "maxIdleClients": 1,
            "activeClients": {},
            "failedClients": {},
            "terminated": false,
            "terminateDeferred": {
                "promise": {}
            }
        }
    },
    "_queryOptions": {
        "parentPath": {
            "segments": []
        },
        "collectionId": "posts",
        "converter": {},
        "allDescendants": false,
        "fieldFilters": [],
        "fieldOrders": [
            {
                "field": {
                    "segments": [
                        "createdAt"
                    ]
                },
                "direction": "DESCENDING"
            }
        ],
        "kindless": false
    },
    "_serializer": {
        "allowUndefined": false
    },
    "_allowUndefined": false
},
"_readTime": {
    "_seconds": 1622395245,
    "_nanoseconds": 513743000
},
"_size": 0,
"_materializedDocs": null,
"_materializedChanges": null
}

Notice how the request for the collection "users" works successfully:

const db = admin.firestore();

exports.getAllUsers = (req, res) => {

 db.collection('users')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {  
   let users = [];
   snapshot.forEach((doc) => {
     let users = [];
     snapshot.forEach((doc) => {
      users.push({
        id: doc.data().userId,
        email: doc.data().email,
        handle: doc.data().handle
     });
   });
  return res.json(users);
})
.catch(err => {
  console.error(err);
  res.status(500).json({ error: err.code });
});
}

And the response:

[
{
    "id": "EPoHBxhQFUXbcL3TCVx1LdUG2nO2",
    "email": "[email protected]"
},
{
    "id": "RqEa3dEq8TSDcZYeolXafju67rB2",
    "email": "[email protected]"
},
{
    "id": "dxveb4n2iMQej5Q14uprsKRxFp23",
    "email": "[email protected]",
    "handle": "user4"
},
{
    "id": "YQPzBPcsqlVZk9iJEuZTHKUNuVG2",
    "email": "[email protected]",
    "handle": "user2"
},
{
    "id": "CZ05BJxi3TUOpIrmBaz539OWlbC3",
    "email": "[email protected]",
    "handle": "user"
},
{
    "id": "t0t83BVwt4gVgJkDv7HL1r1MaKr1",
    "email": "[email protected]",
    "handle": "Jose"
}
]

This is what the users collection looks like in Firebase: Users collection screenshot

Why is one collection failing when the other works fine and I'm using the same code? What am I missing here?

Thanks in advance and I hope I've made it as clear as possible. Please let me know if you need me to provide anything else.



Solution 1:[1]

Very simple my friend, your posts documents can't be ordered like this:

.orderBy('createdAt', 'desc')

Because the post documents does not have the createdAt property, but they have a timestamp property, you should use that property to order your posts like this:

.orderBy('timestamp', 'desc')

I hope that helps ?

Solution 2:[2]

I am not answering directly to @Ruben Garcia Bri, but for future firebase developers who may run into the problem of getting empty documents, I also ran into the same problem, but I solved it by adding a field to the particular document I am trying to retrieve.

Sometimes the cause is because the documents you are trying to get have no field in them.

I mean that a document must have a field before the server can recognize it as an existing document.

So if you run into this problem, consider adding a field to that document before you can successfully retrieve it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sean Gonzalez
Solution 2 Adam Genshaft