1

I want to push an object in array field of Firebase database.

I've tried,

  const friendObj = {
    first_name: item.first_name,
    last_name: item.last_name,
    username: item.username,
    phoneNumber: item.phoneNumber,
    email: item.email,
  }
  db.collection('users')
    .doc('documentId')
    .set({ friends: friendObj })

I want to add an object in friends array of below table. My firebase table looks like below enter image description here

Can anyone please help me, I'm having difficulty while add value in DB.

Hardik Virani
  • 1,687
  • 7
  • 23
  • 36
  • I've never used a firebase database, but could it be that your are not passing the email? making the query fail? – Auticcat Aug 28 '19 at 12:11
  • does'n matter @Auticcat – Hardik Virani Aug 28 '19 at 12:14
  • You can pass array data directly instead. https://cloud.google.com/firestore/docs/manage-data/add-data `var docData = { stringExample: "Hello world!", booleanExample: true, numberExample: 3.14159265, dateExample: firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815")), arrayExample: [5, true, "hello"], nullExample: null, objectExample: { a: 5, b: { nested: "foo" } } }; db.collection("data").doc("one").set(docData).then(function() { console.log("Document successfully written!"); });` – Sunil tc Aug 28 '19 at 12:41
  • @Suniltc i've one object in array and i want to push other one! – Hardik Virani Aug 28 '19 at 12:44
  • This answer might help you. https://stackoverflow.com/questions/47295541/cloud-firestore-update-fields-in-nested-objects-with-dynamic-key – Sunil tc Aug 28 '19 at 18:30

1 Answers1

-1

Firebase doesn't actually have a data type as arrays, but you have few alternatives to store data as an array using an alternative (like sets) and there are methods specifically to work with those.

Check this link for an implementation https://stackoverflow.com/a/40055996/11945277

  • 1
    firebase has data type array @Asela – Hardik Virani Aug 28 '19 at 12:39
  • 1
    This isn't true. They do have arrays, and you can add things to them from the dashboard. – daraul Sep 20 '19 at 17:43
  • @HardikVirani sorry to disappoint you guys, you can call it an array but technically its a different story as i mentioned. kindly follow the links i have shared and do some further reading on it too. here's something from the official blog : https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html – Asela Wijesinghe Sep 22 '19 at 19:02