0

unfornately i should insert record with parentid into realtime databse in firebase

this is my sample added record in chat collection that messageId and key of parent is same

  "-N6w7t_jTLazBcbLnIau": {
  "content": "Test message 1",
  "fromId": "Yto2rkMyXJNVkWS3xAOJgUjXFzI3",
  "messageId": "-N6w7t_jTLazBcbLnIau",
  "phone": "+989034015019",
  "timestamp": "1657792676492",
  "toId": "0FXpksPdL4OAf9KAXx9B0R6nzmh2",
  "type": "1"
},
"-N6w8651yjmhOKRHd5xG": {
  "content": "Test massege 2",
  "fromId": "Yto2rkMyXJNVkWS3xAOJgUjXFzI3",
  "messageId": "-N6w8651yjmhOKRHd5xG",
  "phone": "+989034015019",
  "timestamp": "1657792676592",
  "toId": "0FXpksPdL4OAf9KAXx9B0R6nzmh2",
  "type": "1"
},

and this is my code in java script

firebaseDb.ref('chat/' + state.userDetails.userId ).push(payload.message)

but how i should get ky of my parent id or push key before insert??

Mostafa Asadi
  • 17
  • 1
  • 4

1 Answers1

1

The Firebase push() method can either be invoked with a payload, in which case it writes the payload to a new child in the database, or without a payload, in which case it returns a reference to a new child. Knowing that, you can do:

const newChildRef = firebaseDb.ref('chat/' + state.userDetails.userId ).push();
payload.message.pushId = newChildRef.key;
newChildRef.set(payload.message);

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thank you so much mr.frank. that is true but i want know the Philosophy of this type of insert. do you see problem in design of this collection? – Mostafa Asadi Jul 24 '22 at 10:44
  • Sorry, I'm not sure what you're asking there. In your original post you asked "how i should get [key] of my parent id or push key before insert?", and my answer here and the links show how to do that. – Frank van Puffelen Jul 24 '22 at 14:12
  • tankyou for your answer. my problem solved by your answer but i ask that why i should get key or pushkey in realtime db before insert! that is my personal ask in one project that others designed. – Mostafa Asadi Jul 26 '22 at 06:31
  • Some devs like having the key inside the data too, so that they can get by with just using the value of a snapshot upon reading the data (so not using the key of the snapshot). I prefer not duplicating this part of the data, but (as you can probably tell from my phrasing) it's a preference and not a hard rule. – Frank van Puffelen Jul 26 '22 at 13:54