Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create collection in Cloud Firestore from Javascript?

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.

like image 891
Tomasz.ST Avatar asked Dec 18 '17 15:12

Tomasz.ST


2 Answers

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

like image 129
Greg_M Avatar answered Oct 23 '22 21:10

Greg_M


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);
like image 33
npfoss Avatar answered Oct 23 '22 20:10

npfoss