admin管理员组

文章数量:1289866

I need to create a new object with a generated key and update some other locations, and it should be atomic. Is there some way to do a push with a multi-location update, or do I have to use the old transaction method? This applies for any client platform, but here's an example in JavaScript.

var newData = {};
newData['/users/' + uid + '/last_update'] = Firebase.ServerValue.TIMESTAMP;
newData['/notes/' + /* NEW KEY ??? */] = {
  user: uid,
  ...
};
ref.update(newData);

I need to create a new object with a generated key and update some other locations, and it should be atomic. Is there some way to do a push with a multi-location update, or do I have to use the old transaction method? This applies for any client platform, but here's an example in JavaScript.

var newData = {};
newData['/users/' + uid + '/last_update'] = Firebase.ServerValue.TIMESTAMP;
newData['/notes/' + /* NEW KEY ??? */] = {
  user: uid,
  ...
};
ref.update(newData);
Share Improve this question edited Mar 13, 2018 at 13:44 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges asked Apr 21, 2016 at 15:27 TravisTravis 2,4622 gold badges24 silver badges41 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

There are two ways to invoke push in Firebase's JavaScript SDK.

  1. using push(newObject). This will generate a new push id and write the data at the location with that id.

  2. using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side operation.

Knowing #2, you can easily get a new push id client-side with:

var newKey = ref.push().key(); // on newer versions ref.push().key;

You can then use this key in your multi-location update.

I'm posting this to save some of future readers' time.

Frank van Puffelen 's answer (many many thanks to this guy!) uses key(), but it should be key.

key() throws TypeError: ref.push(...).key is not a function.

Also note that key gives the last part of a path, so the actual ref that you get it from is irrelevant.

Here is a generic example:

var ref = firebase.database().ref('this/is/irrelevant')

var key1 = ref.push().key // L33TP4THabcabcabcabc
var key2 = ref.push().key // L33TP4THxyzxyzxyzxyz

var updates = {};
updates['path1/'+key1] = 'value1'
updates['path2/'+key2] = 'value2'

ref.update(updates);

that would create this:

{
  'path1':
  {
    'L33TP4THabcabcabcabc': 'value1'
  },
  'path2':
  {
    'L33TP4THxyzxyzxyzxyz': 'value2'
  }
}

I'm new to firebase, please correct me if I'm wrong.

本文标签: javascriptFirebase Can I combine a push with a multilocation updateStack Overflow