Smart way to push object to firebase

2020-04-17 07:30发布

问题:

I have an object that I want to push to the firebase realtime database, looking like this:

userProfile = { name: "Jon", age: 25, gender: "male", ...plenty more attributes}

If I want it in firebase, I could write it like this:

return firebase.database().ref('/userProfile').push({
    name: userProfile.name,
    age: userProfile.age,
    gender: userProfile.gender,
    ....
}).

But since I have plenty of objects with many attributes I would prefer not writing it by hand. Loops are not allowed in push (). I could push the whole object like this:

return firebase.database().ref('/userProfile').push({
    userProfile: userProfile
}).

But it will create an additional child node like

ref/userProfile/123someId/userProfile/name

which is bad practise because it disallows using filters and more later on.

Is there a more effective way to push the attributes of an entire object without writing down every key/value pair?

回答1:

The answer could not be easier, but in case someone else stumbles across the same issue:

firebase.database().ref('/userProfile').push(userProfile)

Thanks guys