Angularfire 在没有数据键的情况下将数据附加到数据库中的数组
Angularfire append data to array in database without data key
我正在尝试使用如下所示的数据模型向 rooms/users 添加内容:
rooms: {
name: roomname
users: {
0: email@email.com
}
}
我的问题是是否有任何方法可以将新项目附加到用户数组。我通常会使用 update() 来执行此操作,但是当我只想将数据设置为下一个数组索引时,update() 需要一个键来设置数据。我想我可以通过获取当前 rooms/users 数组,在本地附加它,并使用 set() 覆盖它来做到这一点,但我想知道是否有更好的(内置)方法来解决这个问题.
在 Firebase 等潜在的大规模分布式系统中使用数组通常不是一个好主意。根据您的描述,您的用例属于“一般”类别。
来自Firebase documentation on arrays:
Why not just provide full array support? Since array indices are not permanent, unique IDs, concurrent real-time editing will always be problematic.
Consider, for example, if three users simultaneously updated an array on a remote service. If user A attempts to change the value at key 2, user B attempts to move it, and user C attempts to change it, the results could be disastrous. For example, among many other ways this could fail, here's one:
// starting data
['a', 'b', 'c', 'd', 'e']
// record at key 2 moved to position 5 by user A
// record at key 2 is removed by user B
// record at key 2 is updated by user C to foo
// what ideally should have happened
['a', 'b', 'd', 'e']
// what actually happened
['a', 'c', 'foo', 'b']
Firebase 没有使用数组,而是使用了一个称为“推送 ID”的概念。这些一直在增加(如数组索引),但(与数组索引不同)您不必知道当前计数即可添加新的推送 ID。
使用推送 ID,您可以添加新用户:
var ref = new Firebase('https://yours.firebaseio.com/rooms/users');
ref.push('email@email.com');
请注意,Firebase 文档通常被认为非常好。我强烈建议您至少遵循我从中复制以上内容的 programming guide for JavaScript。
我正在尝试使用如下所示的数据模型向 rooms/users 添加内容:
rooms: {
name: roomname
users: {
0: email@email.com
}
}
我的问题是是否有任何方法可以将新项目附加到用户数组。我通常会使用 update() 来执行此操作,但是当我只想将数据设置为下一个数组索引时,update() 需要一个键来设置数据。我想我可以通过获取当前 rooms/users 数组,在本地附加它,并使用 set() 覆盖它来做到这一点,但我想知道是否有更好的(内置)方法来解决这个问题.
在 Firebase 等潜在的大规模分布式系统中使用数组通常不是一个好主意。根据您的描述,您的用例属于“一般”类别。
来自Firebase documentation on arrays:
Why not just provide full array support? Since array indices are not permanent, unique IDs, concurrent real-time editing will always be problematic.
Consider, for example, if three users simultaneously updated an array on a remote service. If user A attempts to change the value at key 2, user B attempts to move it, and user C attempts to change it, the results could be disastrous. For example, among many other ways this could fail, here's one:
// starting data
['a', 'b', 'c', 'd', 'e']
// record at key 2 moved to position 5 by user A
// record at key 2 is removed by user B
// record at key 2 is updated by user C to foo
// what ideally should have happened
['a', 'b', 'd', 'e']
// what actually happened
['a', 'c', 'foo', 'b']
Firebase 没有使用数组,而是使用了一个称为“推送 ID”的概念。这些一直在增加(如数组索引),但(与数组索引不同)您不必知道当前计数即可添加新的推送 ID。
使用推送 ID,您可以添加新用户:
var ref = new Firebase('https://yours.firebaseio.com/rooms/users');
ref.push('email@email.com');
请注意,Firebase 文档通常被认为非常好。我强烈建议您至少遵循我从中复制以上内容的 programming guide for JavaScript。