Waggoner_Keith
Waggoner_Keith

Reputation: 600

Cloud Firestore Data Query

I am trying to query the below data structure for only documents that contain a map with a certain key. For example, I would want to query the collection "user-picks" only for documents which a contain a field with key "2020-09-16T12:10:00-05:00-987346-10923".

enter image description here

Is this possible in Node.js?

I have tried:

const userPicksRef = firestore.collection('user-picks').where('gameId', '==', String(gameId))
const snapshot = await userPicksRef.get();
snapshot.forEach(doc => {
    console.log(doc.id, " => ", doc.data());
});

After verifying the gameId was correct this returned nothing. I would rather query off the key of the field than the gameId though, although they are the same?

Upvotes: 0

Views: 35

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

Your query isn't going to work because you haven't identified the full path of the field that contains the data you want. Your fields are nested in maps, and Firestore requires that you know the full name of the nested field in order to use it in a query. So, the only way you can find a certain game ID is to also know the name of the field with the formatted date, and reference it with dot notation. Firestore will not wildcard any part of the full field name, or search deeply in fields for you.

If you don't know the full name of the field to use for an equality query, you will have to restructure your data. If you want to be able to search for any game ID that was added to a document, you could add a new array field and populate it with the game ID strings that you want to find. Duplicating data like this to satisfy a specific query is common in Firestore.

If you had a new top-level array field called gameIds populated with strings, you could query it with an array-contains query:

const userPicksRef = firestore
    .collection('user-picks')
    .where('gameIds', 'array-contains', gameId)

Upvotes: 1

Related Questions