1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Firestore】データの登録、取得ができないエラーについて

Posted at

エラー内容

Error: {"code":"permission-denied","name":"FirebaseError"}

Firestoreにデータを登録、またそのデータを取得しようとしましたが、上記エラーが出てきました。

関連するロジック

上記記事を参考に、以下ロジックを導入。

sample.tsx
// 一部省略してます

import { db } from "../../firebase";
import firebase from "firebase/compat/app";

(async () => {
  try {
    const userRef = await db.collection('users').add({
      name: {
        first: 'tarou',
        last: 'yamada',
      },
      score: 80,
      birthday: firebase.firestore.Timestamp.fromDate(new Date(1980, 10, 15)),
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
    })
    const userDoc = await userRef.get()
    console.log(userDoc.data())
  } catch (err) {
    console.log(`Error: ${JSON.stringify(err)}`)
  }
})()

エラー解決手順

まず冒頭で示したエラーの文章そのままで、Google検索してみました。

Error: {"code":"permission-denied","name":"FirebaseError"}

そこで出てきたこちら↑↑の記事内に、関連してそうな箇所を見つけました。

Firestoreにセキュリティルールを設定する

という項目を見つけ、その中の

service cloud.firestore {
  match /databases/{database}/documents {
    match /chatroom/room2/messages/{document} {
      allow read:  if true;
      allow write: if request.auth.uid != null;
    }
  }
}

この箇所を参考にして、

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read:  if true;
      allow write: if request.auth.uid != null;
    }
  }
}

このように書き換えてみました。

結果

その結果、エラーは無事解消され、firestoreにデータが保存されました。

まとめ

現在webアプリを制作中ですが、firebaseの機能を使って、誰かの役に立つようなアプリを作れるように頑張ります。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?