John Doe
John Doe

Reputation: 460

Firebase - unable to nest a collection of collection

In my React Native project I am using Firestore as my database. Whenever a user registers I want to create a supervisor approval request.

Basically under a collection of supervisorRequests there should be a document for each supervisor, named after the supervisor's key. Under the supervisor document I want to have a collection of randomly generated ids which each hold the request metadata. Here is my desired structure:

-supervisorRequests
      -supervisor-1-Key
           -random-id-of-request
              - user: userID
              - userEmail: userEmail
              - requestDate: timestamp
           -random-id-of-request
              - user: userID
              - userEmail: userEmail
              - requestDate: timestamp
      -supervisor-2-Key
           -random-id-of-request
              - user: userID
              - userEmail: userEmail
              - requestDate: timestamp
           -random-id-of-request
              - user: userID
              - userEmail: userEmail
              - requestDate: timestamp
           -random-id-of-request
              - user: userID
              - userEmail: userEmail
              - requestDate: timestamp

My code trying to achieve this is:

const docReference = firebase.firestore().collection(`supervisorRequests`).doc(this.props.supervisorKey);
docReference.set({ user: this.props.userUID, requestDate: new Date().getTime(), userEmail: this.props.email });

My code, however, generates the following structure:

-supervisorRequests
      -supervisor-1-Key
          - user: userID
          - userEmail: userEmail
          - requestDate: timestamp

This is not what I want since every time a new request is made to the supervisor's key, the old request is overriden.

What would be wrong with my code and how can I achieve the first database structure I have presented?

Upvotes: 1

Views: 121

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83181

Just to complete Doug's answer, note that you can directly pass a "slash-separated path" to the doc() method, in order to get "a DocumentReference instance that refers to the document at the specified path".

So you could also do:

firebase.firestore().doc(`supervisorRequests/${this.props.supervisorKey}`).set();

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317808

The string you pass to collection() must be a path to a collection. What you're passing now is the path to a document. It discerns this by seeing the forward slash in the string. Perhaps you want to reference the document like this instead:

firebase.firestore()
        .collection('supervisorRequests')
        .doc(this.props.supervisorKey)

You can use the returned DocumentReference to create the document with its set() method.

Upvotes: 1

Related Questions