【发布时间】:2019-04-13 14:19:17
【问题描述】:
我的 Firestore 数据结构如下:
我想在trend_score 孩子上运行Transaction()。在添加第二个 .then(result => 之前,我的函数正在运行,这意味着现在我向云函数添加了另一个方法,我收到了一个错误:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.handler = functions.firestore.document('/Polls/{pollId}/responses/{userId}').onCreate((data, context) => {
const answerSelected = data.data().answer;
const answerRef = admin.firestore().doc(`Polls/${context.params.pollId}/answers/${answerSelected}`);
const voteCountRef = admin.firestore().doc(`Polls/${context.params.pollId}`);
const trendScoreRef = admin.firestore.doc(`Polls/${context.params.pollId}/trend_score`);
return admin.firestore().runTransaction(t => {
return t.get(answerRef)
.then(doc => {
if (doc.data()) {
t.update(answerRef, { vote_count: doc.data().vote_count + 1 });
}
})
}).then(result => {
return admin.firestore().runTransaction(t => {
return t.get(voteCountRef)
.then(doc => {
if (doc.data()) {
t.update(voteCountRef, {vote_count:doc.data().vote_count+1});
}
});
});
//starting with this set, I believe this code has caused the issue
}).then(result => {
return admin.firestore().runTransaction(t => {
return t.get(trendScoreRef)
.then(doc => {
if (doc.data()) {
t.update(trendScoreRef, {trend_score:doc.data().trend_score+1});
}
});
});
});
错误
1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/troychuinard/.npm/_logs/2018-11-10T02_02_56_229Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
[1]: https://i.stack.imgur.com/etVwy.png
【问题讨论】:
-
您的问题没有显示控制台的所有相关输出,但我现在可以告诉您,eslint 抱怨您嵌套了
then回调,这被认为是不好的样式并且容易出现错误。 -
知道了,所以与其添加额外的 then 回调,我应该在第一个回调的底部添加另一个 t.update 吗?或者最佳实践是一个单独的功能?本质上,我想用 1 种方法更新 2 个位置
-
只需将其添加为链中的另一个
then即可,如dup所示。 -
这不是我所做的吗?
-
不,您已经将
then回调嵌套在内部 其他thens 而不是在 它们之后。
标签: node.js firebase google-cloud-functions