简体   繁体   中英

How to update document in firestore?

I read some post how to update document in firebase but it doesn't work for me. 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. 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 .

Notice the difference in the examples provided in the the official docs for creating a new document in the collection via 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? 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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