![](/img/trans.png)
[英]How to get only one element from an array (firebase database, nodejs)
[英]How to set only ONE element in an array in firebase
我在firebase上保存了一个数组,如下所示:
matches:[ {match:{id:1,data:...}}]
我只想在此阵列的Firebase上保存一项。 例如,我的比赛ID为:32。 我想在保存在Firebase中的阵列上找到它,然后进行更改。
我正在努力做到这一点。 但是我认为,向firebase发出请求,复制数组并再次保存整个数组非常麻烦。
const ref = `/users/${currentUser.uid}/matches`;
var list = [];
firebase.database().ref(ref).on('value', function (snap) { list = snap.val(); });
if (list.length > 0) {
const indexToUpdate = list.findIndex(k => k.name == match.name)
if (indexToUpdate >= 0) {
list[indexToUpdate] = match;
return dispatch => {
firebase
.database()
.ref(`/users/${currentUser.uid}/matches`)
.set(list)
.then(() => {
dispatch({ type: MATCH_UPDATE, payload: match });
});
};
}
}
有灯吗
这行代码:
const indexToUpdate = list.findIndex(k => k.name == match.name)
您的数据结构不理想是一个死胡同。
考虑将匹配项存储在其名称下,并在其前面加上字符串以防止Kenneth提到的数组强制。 所以:
matches
match1
date: "2018-06-14..."
...
match2
date: "2018-06-16..."
...
这样,您无需查询即可查找节点是否匹配。 它还会阻止使用数组,正是由于您提到的原因,数组才在Firebase中成为反模式。
有关更多信息,请参见经典的Firebase博客文章“ 最佳实践:Firebase中的数组” 。
如果密钥的数字顺序正确,Firebase将数组存储为对象,并在返回客户端时将其转换回数组
但是从根本上说,它应该可以与您要更新的对象建立相同的路径。
firebase
.database()
.ref(`/users/${currentUser.uid}/matches/${indexToUpdate}`)
.set(match)
.then(() => {
dispatch({ type: MATCH_UPDATE, payload: match });
});
您需要通过URL中的ID引用您要设置的商品的ID
firebase
.database()
.ref(`/users/${currentUser.uid}/matches/32`)
.set(list)
.then(() => {
dispatch({ type: MATCH_UPDATE, payload: match });
});
另外,如果索引不起作用,请使用snap.key获取所需的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.