【发布时间】:2019-02-11 04:19:05
【问题描述】:
我正在使用 Firebase Functions Shell 在 Node 中本地测试 Firestore 触发的 Firebase Cloud Function。
当使用 onWrite 触发器并通过从函数 shell 调用 updateMonth({foo:'new'}) 传递新文档时,我无法获得对新文档的引用。
exports.updateMonth = functions.firestore
.document('users/{userId}').onWrite((change, context) => {
const document = change.after.exists ? change.after.data() : null;
console.log("change.after.exists", change.after.exists)
console.log("change.before.exists", change.before.exists)
const oldDocument = change.before.data();
console.log("Old:",oldDocument)
return true
})
当同时调用 before 和 after 来模拟文档更新 updateMonth({before:{foo:'old'},after:{foo:'new'}}) 时,它按预期工作。
但是,当仅使用 updateMonth({foo:'new'}) 调用时,前后文档似乎都不存在:
i functions: Preparing to emulate functions.
Warning: You're using Node.js v8.4.0 but Google Cloud Functions only supports v6.11.5.
+ functions: hi
+ functions: helloWorld
+ functions: updateMonth
firebase > updateMonth({before:{foo:'old'},after:{foo:'new'}})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: change.after.exists true
info: change.before.exists true
info: Old: { foo: 'old' }
info: Execution took 20 ms, user function completed successfully
firebase > updateMonth({foo:'new'})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: change.after.exists false
change.before.exists false
Old: undefined
Execution took 2 ms, user function completed successfully
我不确定如何获得对正在创建的新文档的引用。在这种情况下,我希望 change.after.exists 是正确的。
【问题讨论】:
-
您的问题有点身份问题。你说它是一个 onWrite 触发器,但你已经展示了一个 onUpdate 触发器。 onUpdate 仅在修改现有文档时触发,
before和after文档应始终存在。 onWrite 将触发任何更改(您必须小心检查发生了什么)。你想在这里完成什么? -
我的错。感谢您指出 Doug,我已经使用 onWrite 触发器再次测试了代码,并添加了完整的控制台输出以进行澄清。
标签: node.js firebase google-cloud-firestore google-cloud-functions firebase-cli