简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM