How to create collection in Cloud Firestore from Javascript?

17,438

Solution 1

You cannot create empty collection, you have to create document inside. data model

function writeUserData(userId, name, email, imageUrl) {
      firebase.database().ref('users/' + userId).set({
        username: name,
        email: email,
        profile_picture : imageUrl
      });
    }

You can get user id in this way

var userId = firebase.auth().currentUser.uid;

For cloud firestore

db.doc(userId + '/data').set({
  name: name,
  email: email
});

firebase doc - read&write

Solution 2

I was trying to create a collection within a document and the accepted answer didn't work for me, but this did:

db
    .collection("coll1")
    .doc("doc1")
    .collection("newCollectionName")
    .doc("newDocName")
    .set(data);
Share:
17,438
Tomasz.ST
Author by

Tomasz.ST

Updated on June 14, 2022

Comments

  • Tomasz.ST
    Tomasz.ST almost 2 years

    When user creates account in my angular app, my app creates user account (using Firebase API) with email and password. But also I want to create new collection to hold more data like name, surname...

    Each collection's name will have uid. But I don't know how to force it? db.createCollection('abcXdefX') doesn't exist. I've no idea what to do. Please, help.