0

Here is my code:

function saveID(sender_psid,count){
   let data = new Object();
   data.ID = sender_psid[count];
   db.collection('users').doc('ID').set(data);
}

I am trying to add data to my firestore database. My current code does that but each time the function is called the new data replaces the old one instead of adding itself to the database. How do I fix that?

2
  • 1
    Did you read the docs? It looks like set will write or replace data. Looks like you need to use push. push will create an id for you. firebase.google.com/docs/database/admin/save-data Commented Jul 9, 2018 at 20:16
  • 1
    push is for the realtime database, not for Firestore (which OP is using because they reference collection). but same principal! Commented Jul 9, 2018 at 20:32

1 Answer 1

3

If you want to update the existing data, use update(data) instead of set

If you want to put a new document there, you can use collection('users').add(data) and it will use an auto generated id for the new document.

You can also add a new document to the collection by specifying a different document id to set: collection('users').doc(id).set(data). In this case, id has to be a variable. Basically if you use set on a document without the merge option, you are setting the data for the specified document id. So if you use the same document id, it will overwrite the document (unless you specify the merge parameter). If you use a different id, it will add a new document using your specified id.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.