编译Firebase云函数时出现eslint解析错误Unexpected token sellGrpRef求助
问题原因及解决方案
直接报错根源
你在代码中使用了await关键字,但对应的onCreate回调函数没有声明为async,这是触发Unexpected token sellGrpRef解析错误的核心原因:JS引擎遇到未在async函数内的await关键字时,会把后续代码识别为非法语法,因此抛出token解析异常。
其他需要修正的代码问题
- 你所用的Admin SDK 命名空间式API不存在
whereEqualTo、whereLessThanOrEqualTo这类方法,统一使用where方法传入运算符即可 - 你对
status字段同时设置了等于1和等于5的过滤条件,逻辑互斥,永远查不到结果,应该改用in数组查询 snapshot.data()返回的是普通JS对象,不需要调用getXXX()方法取值,直接访问对应属性即可- 多条件+排序的复合查询需要提前在Firestore控制台创建对应的复合索引,否则运行时会抛出索引缺失的报错
修正后完整代码
// 给回调函数添加async关键字 exports.findDealsOnBuy = functions.firestore .document('businessmen/{businessmenId}/buy/{buyId}') .onCreate(async (snapshot, context) => { const businessmenId = context.params.businessmenId; const buyId = context.params.buyId; const buy = snapshot.data(); functions.logger.info('businessmenId : ', businessmenId, ' buyId : ', buyId, ' buy : ', buy ); const sellGrpRef = admin.firestore().collectionGroup('sell'); // 修正查询方法、逻辑条件、取值方式 const querySnapshot = await sellGrpRef .where('goodsName', '==', buy.goodsName) .where('goodsLocation', '==', buy.goodsLocation) // 用in查询匹配status为1或5的文档 .where('status', 'in', [1,5]) .where('bestPrice', '<=', buy.bestPrice) .orderBy('bestPrice', 'desc') .get(); if (querySnapshot.empty) { console.log('No matching documents.'); return; } querySnapshot.forEach((doc) => { console.log(doc.id, ' => ', doc.data()); }); });
后续操作提示
代码修正后部署时如果出现索引缺失的报错,直接复制报错信息里的索引创建路径,在Firestore控制台手动创建对应索引,等索引构建完成后功能即可正常运行。
内容的提问来源于stack exchange,提问作者Suman Mondal
相关产品推荐
相关产品推荐

