0
votes

I asked a question about a similar topic and it is answered, but have some problems again so they told me to ask under another topic.

I'm trying to add data to the Firestore cloud with UID. I have the UID, and add with UID without a problem, but when I want to add another one it deletes the old data and rewrites on it. I want to add multiple data under the same UID.

$('#form').submit(function(e) {
e.preventDefault();
let name = $('[name = name]').val();
let cityLAT = $('[name = cityLAT]').val();
let cityLONG = $('[name = cityLONG]').val();
let user = firebase.auth().currentUser;
let uid;
if(user != null) {
    uid = user.uid;
}
const ref = db.collection('campaigns').doc(uid);
ref.set({ name: name,
cityLAT: cityLAT,
cityLONG: cityLONG },{ merge: true });
$('[name = name]').val('');
$('[name = cityLAT]').val('');
$('[name = cityLONG]').val('');
1
What exactly do you mean by "add multiple datas"? What is your desired result? - Doug Stevenson
One thing to note is that using .set() will replace whatever data is currently stored in your document with the new data that you provide. It is possible that you will need a solution using .update(), but it is unclear what you are trying to achieve. What do you expect the data in Firestore to look like after you "add another one"? - Herohtar
I want to say that when I add a data to firestore, I dont want to delete the old data, add data with same uid which signed in users id. My existing code deletes the old one and writes new data. I dont want to delete anything just add more with same uid. - user10894226

1 Answers

0
votes

If you want to "add data with same uid" (i.e. add data to the document with the following DocumentReference: db.collection('campaigns').doc(uid)) you have two possibilities:

  1. Use the update() method which "updates fields in the document referred to by this DocumentReference". However, you have to know that "the update will fail if applied to a document that does not exist."
  2. Use the set() method with the merge option, which will work even if the doc does not exist. See also this doc: https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document

So, in your case, using the set() method as explained above would look like:

const ref = db.collection('campaigns').doc(uid);
ref.set(
   { name: name,
     cityLAT: cityLAT,
     cityLONG: cityLONG },
   { merge: true }
);