Firebase 云函数 Firestore 触发 onWrite 在本地测试时未按预期运行

sma*_*ert 5 node.js firebase google-cloud-functions google-cloud-firestore firebase-cli

我正在使用 Firebase Functions Shell 在 Node 中本地测试 Firestore 触发的 Firebase Cloud Function。

当使用 onWrite 触发器并通过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
})
Run Code Online (Sandbox Code Playgroud)

当同时使用 before 和 after 来模拟文档更新时,updateMonth({before:{foo:'old'},after:{foo:'new'}})它会按预期工作。但是,当使用 just 调用时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
Run Code Online (Sandbox Code Playgroud)

我不确定如何获得对正在创建的新文档的引用。在这种情况下,我希望 change.after.exists 为真。

Dou*_*son 6

使用 onWrite 和 onUpdate 触发器,您需要在所有情况下声明文档的“之前”和“之后”状态。您不能尝试通过省略“before”或“after”键来简化 API。例如,如果您只想测试文档创建,请尝试以下操作:

updateMonth({
    after:{foo:'new'}
})
Run Code Online (Sandbox Code Playgroud)

此外,如果您的代码只对文档创建感兴趣,那么只在 onCreate 触发器上编写可能比在 onWrite 中找出文档状态更容易。就我个人而言,我避免使用 onWrite 并使用其他三个,因为它们更容易推断实际所做的更改。