如何在Firebase Realtime Database规则中为所有用户节点统一设置indexOn
解决方案
1. 安全规则修改(无需逐个新增账户配置)
Firebase 实时数据库规则支持$开头的通配符变量,可匹配任意动态节点名称,你可以直接用通配符匹配所有用户节点,统一配置cart的索引规则:
{ "rules": { ".read": true, ".write": true, // 用$前缀定义通配符,匹配所有*_user格式的节点 "$user_account": { "cart": { ".indexOn": "product/id" } } } }
注意:当前全局
.read和.write都设为true属于极高风险配置,正式环境建议根据用户认证状态限制权限,避免数据被恶意篡改、爬取。
2. 现有代码调整说明
- 你现有拼接用户节点路径的逻辑不需要修改,和上述规则的通配符匹配逻辑完全兼容
- 现有代码存在隐性bug:
itemRef.remove()写在了forEach循环外,且位于异步get的回调非循环体内,部分场景下会出现itemRef还未赋值就执行删除、或者仅删除最后一个匹配商品的问题,建议调整为如下写法:
removeFromCart(itemRemoved){ let account = JSON.parse(localStorage.getItem('user')) === null ? '' : JSON.parse(localStorage.getItem('user')).email account == '' ? account = ['_default', ''] : account = /([^@]+)/.exec(account) const cartRef = firebase.database().ref('/' + account[0] + '_user' + '/cart'); const itemQuery = cartRef.orderByChild("product/id").equalTo(itemRemoved.id); itemQuery.get().then((snapshot) => { snapshot.forEach((productSnapshot) => { // 直接在循环内执行删除,避免赋值异常 productSnapshot.ref.remove() }) }) }
内容的提问来源于stack exchange,提问作者InTeReStInG
相关产品推荐
相关产品推荐

