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 1 year has passed since last update.

【Firebase】DocumentReference型のフィールドの変更を確認する際の注意点

Posted at

特定のパスのコレクションに存在するドキュメントの内容が更新された場合に、その更新されたものがDocumentReferenceだったら古いものを削除するバックグラウンド関数を実装しました。

export const updateUser = functions
    .region(REGION)
    .firestore.document("users/{userId}")
    .onUpdate(async (snapshot, context) => {
        const oldData = snapshot.before.data();
        const newData = snapshot.after.data();
        
        if (
            "imageRef" in oldData &&
            "imageRef" in newData &&
            oldData.imageRef != newData.imageRef &&
            oldData.imageRef != null &&
            newData.imageRef != null
        ) {
            // 古いimageRefを削除する
            // ...
        }
    });

しかし、上記の条件だと、imageRefが更新されていないにもかかわらず現在のimageRefが参照するドキュメントが削除されてしまう現象に見舞われました。

実は、上記の条件の部分で1箇所だけ必ずtrueになってしまう部分があります。

それがこちらです。

oldData.imageRef != newData.imageRef

もし、値に変更がないか比較したいのであれば、次のようにpathを比較するべきなのでした。

oldData.imageRef.path != newData.imageRef.path

最終的な条件文は次のとおりです。

const oldData = snapshot.before.data();
const newData = snapshot.after.data();

if (
    "imageRef" in oldData &&
    "imageRef" in newData &&
    oldData.imageRef.path != newData.imageRef.path &&
    oldData.imageRef != null &&
    newData.imageRef != null
) {
    // 古いimageRefを削除する
    // ...
}

みなさんもDocumentReference型のフィールドを比較するときは、pathまで含めて比較するようにしましょう。。。さもないと僕みたいに時間を溶かすことになります。。。

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?