0

「広告」という名前のコレクションがあります

/adverts/{advert_id} <-- advert_id は firestore によって自動生成されます。

そして、コレクション "users" /user/{user_id} <--- user_id はユーザー名によって定義されます

したがって、「広告」ドキュメント内に次のマップがあります

user_data:{
    avatar_url: "",
    first_name: "example name",
    last_name: "example last name",
    rating: 5,
    username: "exampleusername"
}

この情報は、広告が作成されるたびにユーザー ドキュメントから取得されます。したがって、ユーザーがデータを更新するたびに、広告コレクションでこのマップを更新したいと考えています。

広告に複数のドキュメントが存在する可能性があると仮定して、このフィールドをバッチで更新することは可能ですか? (すべてのファイルを読み取らずに書き直そうとしています。書きたいだけです)

私はこれを達成しようとしていました(onUpdateクラウド関数です):

const before = change.before.data(); // Data before the update
const after = change.after.data(); // Data after the update
const user_id = after.username;

let batch  = db.batch()
let advertsRef = db.collection("adverts").where("user_data.username", "==", user_id)

batch.update(advertsRef, {
    "user_data.avatar_url": after.avatar_url,
    "user_data.first_name": after.first_name,
    "user_data.last_name": after.last_name,
    "user_data.overall_adverts_rating": after.overall_adverts_rating,
    "user_data.username": after.username,
 })

batch.commit().then(()=>{
  console.log("done")
})
.catch(error =>{
  console.log(error)
})

しかし、次のエラーが発生します。

Error: Value for argument "documentRef" is not a valid DocumentReference.
at Object.validateDocumentReference (/workspace/node_modules/@google-cloud/firestore/build/src/reference.js:2034:15)
at WriteBatch.update (/workspace/node_modules/@google-cloud/firestore/build/src/write-batch.js:312:21)
at /workspace/index.js:147:9
at cloudFunction (/workspace/node_modules/firebase-functions/lib/cloud-functions.js:134:23)
at /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:199:28
at processTicksAndRejections (internal/process/task_queues.js:97:5) 

私の .where() が特定のファイルを参照していないことが原因だと思います。

4

1 に答える 1