LoginSignup
1

More than 1 year has passed since last update.

Firestoreのエラー "Converting circular structure to JSON Firebase"

Last updated at Posted at 2020-09-22

エラーの原因

document内で, referenceタイプのフィールドを使っている場合に発生します.

筆者のアプローチ

referenceタイプのフィールドが他のドキュメントを指すことで再帰的になっている為, そのドキュメントのパスを文字列型に変換してあげればいいと思います.
他の方法があればご教授いただきたいです.🙇‍♂️

具体的な方法

下記は取得したいドキュメントの DocumentReferenceを引数として与えてあげるとそのドキュメントをオブジェクトとして返してあげる関数です.

const resolveCirculations = (documentRef) => {
  const data = documentRef.data();
  const circlerRefResolved = Object.keys(data).reduce((ret, key) => {
    ret[key] = has(data[key], 'path') ? data[key].path : data[key];
    return ret;
  }, {});
  return { ...circlerRefResolved, id: documentRef.id };
};

ドキュメントの一件取得は下記のように使ってあげます.

const postRef = await db.collection('posts').doc(id).get();
const post = resolveCirculations(postRef);

ドキュメントを複数(コレクションで)取得したい場合は以下で, CollectionReference 用に関数を用意してあげます.先程のresolveCirculationsを使います.

const getDocs = (collectionRef) =>
collectionRef.docs.map(resolveCirculations);

上記を使うと, 複数件は以下で取得できます.

const usersRef = await db.collection('users').get();
const users = getDocs(usersRef);

以上になります.

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
What you can do with signing up
1