Max888
Max888

Reputation: 3780

Firestore create document if it doesn't exist, and listen to it

I am using the Firebase web client for Firestore. I have a value id that is either the id for a document in a collection, or is undefined. I would like to either create a document with an id generated by Firestore (when id is undefined) or get the document if id is defined, and then listen to changes on the document. I want to be left with a function unsubscribe that I can call to detach the listener. Something like this:

let unsubscribe;
if (recipeId) {
  unsubscribe = db
    .collection("mycollection")
    .doc(id)
    .onSnapshot(doc => myFunction(doc));
} else {
  unsubscribe = db
    .collection("mycollection")
    .doc()
    .add()
    .then(docRef =>
      db
        .collection("mycollection")
        .doc(docRef.id)
        .onSnapshot(doc => myFunction(doc))
    );
}

Upvotes: 0

Views: 651

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317758

To add a new document with a random ID:

  const promise = db
    .collection("mycollection")
    .add({})

add() returns a promise with a DocumentReference. You can then listen to that.

  promise.then((ref) => ref.onSnapshot(...))

Upvotes: 2

Related Questions