节点js:将数据添加到firestore数据库

时间:2022-03-13 08:04:29

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?

我正在尝试将数据添加到我的firestore数据库。我当前的代码执行此操作但每次调用该函数时,新数据将替换旧数据,而不是将其自身添加到数据库中。我该如何解决这个问题?

1 个解决方案

#1


2  

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

如果要更新现有数据,请使用update(data)而不是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.

如果你想在那里放一个新文档,你可以使用集合('用户')。添加(数据),它将使用自动生成的id作为新文档。

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.

您还可以通过指定要设置的其他文档ID来向集合中添加新文档:集合('users')。doc(id).set(data)。在这种情况下,id必须是一个变量。基本上,如果在没有合并选项的文档上使用set,则表示您正在设置指定文档ID的数据。因此,如果您使用相同的文档ID,它将覆盖文档(除非您指定merge参数)。如果您使用不同的ID,它将使用您指定的ID添加新文档。

#1


2  

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

如果要更新现有数据,请使用update(data)而不是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.

如果你想在那里放一个新文档,你可以使用集合('用户')。添加(数据),它将使用自动生成的id作为新文档。

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.

您还可以通过指定要设置的其他文档ID来向集合中添加新文档:集合('users')。doc(id).set(data)。在这种情况下,id必须是一个变量。基本上,如果在没有合并选项的文档上使用set,则表示您正在设置指定文档ID的数据。因此,如果您使用相同的文档ID,它将覆盖文档(除非您指定merge参数)。如果您使用不同的ID,它将使用您指定的ID添加新文档。