FireStore create a document if not exist

前端 未结 2 1210
小蘑菇
小蘑菇 2020-12-24 12:30

I want to update a doc like this:

db.collection(\'users\').doc(user_id).update({foo:\'bar\'})

However, if the doc user_id does not exists,

2条回答
  •  孤城傲影
    2020-12-24 12:35

    If you need things like created and updated timestamps, you can use this technique:

    let id = "abc123";
    let email = "john.doe@gmail.com";
    let name = "John Doe";
    let document = await firebase.firestore().collection("users").doc(id).get();
    if (document && document.exists) {
      await document.ref.update({
        updated: new Date().toISOString()
      });
    }
    else {
      await document.ref.set({
        id: id,
        name: name,
        email: email,
        created: new Date().toISOString(),
        updated: new Date().toISOString()
      }, { merge: true });
    }
    

    This will create the document if it doesn't exist with created and updated timestamps, but only change the updated timestamp if it exists.

提交回复
热议问题