LoginSignup
2
0

More than 1 year has passed since last update.

【Vue × Firestore】自動生成されるドキュメントIDをフィールドに保存する

Last updated at Posted at 2021-06-08

自動生成されるドキュメントIDをフィールドに保存する

実際のコード


     saveBookmark() {
      const id = firebase
        .firestore()
        .collection("users")
        .doc(this.$route.params.uid)
        .collection("bookmarks")
        .doc().id;
      firebase
        .firestore()
        .collection("users") //「users」コレクションを参照
        .doc(this.$route.params.uid) //対象ページのユーザーを参照
        .collection("bookmarks") //「bookmarks」サブコレクションを参照
        .doc(id) //自動生成されたドキュメントIDを参照
        .set({
          postId: this.list.id, //「postId」に投稿データである「this.list.id」を代入。
          time: firebase.firestore.FieldValue.serverTimestamp()
        })
        .then(() => {
          this.$swal("ブックマークに追加しました。", {
            icon: "success"
          });
          this.isBookmarked = true;
        })
        .catch(() => {
          this.$swal("ブックマークを追加出来ません。", {
            icon: "error"
          });
        });
    },

以下のように変数(id)に対象ドキュメントまでのパスを記述して代入する。

       const id = firebase
        .firestore()
        .collection("users")
        .doc(this.$route.params.uid)
        .collection("bookmarks")
        .doc().id;

あとはdoc()時に先ほど代入した「id」を入れて、set()を使って参照する。

※ここで注意。set()を使う理由としてadd()の場合は、IDが自動生成されてしまうので
指定できるset()を使わなければならない。

指定したidを使って、以下のように削除を行える。

firebase
        .firestore()
        .collection("users") //「users」コレクションを参照
        .doc(this.$route.params.uid) //対象ページのユーザーを参照
        .collection("bookmarks") //「bookmarks」サブコレクションを参照
        .doc(id) //自動生成されたドキュメントIDを参照
        .set({
          postId: this.list.id, //「postId」に投稿データである「this.list.id」を代入。
          time: firebase.firestore.FieldValue.serverTimestamp()
        })
        .then(() => {
          this.$swal("ブックマークに追加しました。", {
            icon: "success"
          });
          this.isBookmarked = true;
        })
        .catch(() => {
          this.$swal("ブックマークを追加出来ません。", {
            icon: "error"
          });
        });
    },
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0