1

I can't find how to create a new document without any fields, but one subcollection - messages (and this message collection would have some fields). This is what I want to do. But I don't want to create subcollection in document which already exist. I want to create new document and subcollection in it.

enter image description here

Honestly I stopped on that :

let chatRef = db.collection("chat_event").add({

})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
poldeeek
  • 313
  • 2
  • 16

1 Answers1

2

This answer will greatly help.

let chatRef = db
 .collection("chat_event").document("chat1")
 .collection("messages").document("message1");

If you don't want to hardcode the parent document's id or if you want a firestore generated id. Then get the id first from firestore's createId() function.

let chatEventId = db.createId();
let chatRef = db
 .collection("chat_event").document(chatEventId)
 .collection("messages").document("message1");

You could still use auto-generated id for the subcollection's document:

let chatEventId = db.createId();
let messageId = db.createId();
let chatRef = db
 .collection("chat_event").document(chatEventId)
 .collection("messages").document(messageId);

Note that firestore's autogenerated IDs are entirely random and consequently the documents are not stored in any chronological order. If you will in anyway need some ordering, you could add timestamps to those documents either when you insert data or you update the document with the timestamp info.

docRef.update({
  timestamp: firebase.firestore.FieldValue.serverTimestamp()
});

With that, you can order chronologically both in the console and in your own queries.

Check out this answer for more information on auto-generating IDs

Obum
  • 1,485
  • 3
  • 7
  • 20
  • I saw it, but in this case document "chat1" is already exist. I want to create new document "chat1", but with id which firebase would give me – poldeeek May 30 '20 at 00:01
  • The `chat1` document doesn't have to exist for this code to work. If it doesn't exist yet, no `chat1` **document** is created, but the path comes into existence. I recommend trying it and looking at the result in the console.' – Frank van Puffelen May 30 '20 at 00:30
  • Now I know everything what I wanted :P But I am curious if firebase id is entirely random then is any chance to repeat ? – poldeeek May 30 '20 at 13:04
  • 1
    There's little or no chance to repeat. The use of the random IDs in firestore, was actually to make the ID repetition much less likely in firestore, compared to the real-time database where the IDs where generated with help of time and could possibly have clashes. – Obum May 30 '20 at 13:11