Is There Such A Thing As “Multi-Path Push” in Firebase Real-Time Datasbase?

爷,独闯天下 提交于 2021-02-07 14:20:43

问题


I was watching this video which talks about multi-path updates in Firebase. Multi-path updates are great because they allow you to call the firebaseRef.update() method two or more times while having them be one atomic, all-or-nothing operation.

This is great, but in my current situation I don't want to use the update() method. Instead, I want to use the FirebaseRef's push method and allow Firebase to generate a unique key for my object.

The tricky part is that I have denormalized my data so that it's in two places. What I would really like to do is have an atomic, all-or-nothing operation that uses Firebase's push() operation to create a unique key and then save the object with that key in 2 or more different places inside of my database data. However, the syntax for push() already uses an object so is what I want to do even possible?

Note: Another possible solution may be to use Firebase api to somehow generate a unique key in the client and then do a standard multipath update using that generated key as the key for my object being inserted.


回答1:


There is no multi-location push, but because push IDs are generated on the client, you can use a multi-location update to do what you want.

You can generate a push ID by calling push with no arguments. Push IDs are generated on the client and generating one involves no interaction with the database:

let key = firebase.database().ref().push().key;

You can use AngularFire2 to do this, too; although, you have to pass an argument (undefined) to push to appease TypeScript:

let key = angularFire.database.list('').push(undefined).key;

Once you've generated the key, you can create a multi-location update:

let obj = { some: 'object' };
angularFire.database.object('').update({
    [`a/path/${key}`]: obj,
    [`another/path${key}`]: obj
});

The update is atomic, so either all of the paths will be updated or none will.



来源:https://stackoverflow.com/questions/41490132/is-there-such-a-thing-as-multi-path-push-in-firebase-real-time-datasbase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!