简体   繁体   English

如何在Firestore中更新文件?

[英]How to update document in firestore?

I read some post how to update document in firebase but it doesn't work for me. 我读了一些文章,介绍如何在Firebase中更新文档,但对我而言不起作用。 User have possibility to add document in his database and he should have possibility to update that entry. 用户可以在他的数据库中添加文档,并且他应该可以更新该条目。 Here is my code for now... 这是我现在的代码...

const form = document.querySelector('#database');

form.addEventListener('submit', (e) => {
    e.preventDefault();
    db.collection('database').add({
        field1: form.field1.value,
        field2: form.field2.value 
    });
    db.collection('database').update({
        field2: form.field2.value
    });
})

Your add works because you are creating a new document in that collection. 您的add有效,因为您正在该集合中创建一个新文档。 On the other hand, when you try to update , you have to target which specific document you want to update... updating a collection doesn't make sense, you should be targeting a document . 另一方面,当您尝试update ,您必须定位要更新的特定文档。更新collection没有意义,您应该定位一个document

Notice the difference in the examples provided in the the official docs for creating a new document in the collection via add : 注意官方文档中提供的示例之间的差异,这些示例用于通过add在集合中创建新文档:

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})

vs the example to update a particular document: 与用于更新特定文档的示例:

// Set the "capital" field of the city 'DC'
db.collection("cities").doc("DC").update({
    capital: true
})

Notice how the update targets a particular document? 注意update如何针对特定文档? That's what you need to do. 那就是你需要做的。 I highly suggest you review the official docs for more examples, they're pretty helpful. 我强烈建议您查看官方文档以获取更多示例,它们非常有帮助。

EDIT: 编辑:

To edit a document, you need to know it's name... you can either query the collection to discover the name, or you could use the following method of adding a new document, where you get to set the name yourself. 要编辑文档,您需要知道它的名称...您可以查询集合以发现名称,也可以使用以下添加新文档的方法来自己设置名称。 In this example, they are creating a new "LA" document, with the name&state&country properties: 在此示例中,他们将使用name&state&country属性创建一个新的“ LA”文档:

db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

This way you know the name of your document. 这样,您就知道文档的名称。 By using the add syntax, Firebase will auto-generate the name of the new document. 通过使用add语法,Firebase将自动生成新文档的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM