Search code examples
node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functionsfirebase-admin

Google Firestore Deleting Multiple Fields


I have a firestore. I am trying to delete a specific record from the document 'idAvailable'. However, the id is not deleted from the idAvailable table when we hit this endpoint: http://localhost:5001/us-central1/reserveId which is defined in the below code snippet.

exports.reserveId = functions.https.onRequest(async (req, res) => {
  cors(req, res, ()=> {
    const documentId = "idAvailable"
    const setReserved = "idReserved"
    admin.firestore().collection("Vacancy").doc(documentId).get().then(doc => {

      const field = doc.data().ar[0]
      console.log("Field " + JSON.stringify(field))

      // No error but doesn't execute correctly
      const doDelete = db.collection("Vacancy").doc(documentId).update(field, admin.firestore.FieldValue.delete())

    res.send(doc.data().ar[0])

    }).catch(error => {
      res.send(error)
    })
  })
});

Specifically, this line:

const doDelete = db.collection("Vacancy").doc(documentId).update(field, admin.firestore.FieldValue.delete())

does not delete from the collection.

Why is this happening?


Solution

  • Are you trying to delete an item from an array? You can use arrayRemove instead. Also you can use async-await syntax since your function is async:

    exports.reserveId = functions.https.onRequest(async (req, res) => {
      cors(req, res, async () => {
        const documentId = "idAvailable"
        const setReserved = "idReserved"
        
        const snap = await admin.firestore().collection("Vacancy").doc(documentId).get()
        const field = snap.data().ar[0] // value of that array item
       
        await db.collection("Vacancy").doc(documentId).update({ ar: admin.firestore.FieldValue.arrayRemove(field) })
    
        res.send(doc.data().ar[0]) // response body is deleted from array
      })
    });
    

    Do note that if you know value of that item to be removed (exact same object/string), then you can use arrayRemove directly without fetching the document first.


    If you want to delete multiple fields then you can pass an object like this:

    await db.collection("Vacancy").doc(documentId).update({ 
      field1Name: admin.firestore.FieldValue.delete(),
      field2Name: admin.firestore.FieldValue.delete()
    })