No N
No N

Reputation: 159

How to create a collection inside a document?

I am writing a Flutter application with Firebase. When creating a user I am doing:

Firestore.instance.collection('users').document(user.uid).setData({
        'name': name + ' ' + surname,
        'email': user.email,
        'registerDate' : DateTime.now(),
        'isEmailVerified': user.isEmailVerified,
        'location': location,
        'photoUrl': user.photoUrl,
        'votes' : {},

      });

I want the "votes" to be a collection and contain documents.

Upvotes: 2

Views: 2409

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

How to create a collection inside a document?

If you need a subcollection under your uid document that should contain votes, then use the following lines of code:

Firestore.instance.collection('users').document(user.uid)
    .collection('votes').document(vote)
    .setData({/* ... */});

In which vote is an object that is added under votes subcollection.

If you want to add the collection right after you added the user to the users collection, then check when the setData() operation completes and right after that write the vote object to the above reference.

One more thing to remember is that in Cloud Firestore documents and subcollections don't work like filesystem files and directories. Please also see my answer from the following post:

Firestore document/subcollection is not existing

Upvotes: 2

Related Questions