Jon Doe
Jon Doe

Reputation: 389

Check if field exists, delete it and create a new one

I am trying to write a NodeJS program that on a given document, it checks if a field exists from a given list of fields - lets say the key we are looking for is key1. If the field exists it is deleted and a new field is added with the field incremented - key2 with some value.

// Get the `FieldValue` object
let FieldValue = require('firebase-admin').firestore.FieldValue;

// Create a document reference
let cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
let removeCapital = cityRef.update({
  capital: FieldValue.delete()
});

From the documentation I found the way to delete a field but I am not sure how to check if the key exists so the program knows what key to create after the deletion.

For the program the key might be any sequence of letters followed by a sequence of numbers - key1, key2, key3 etc, so I need a way to know which of those exists in order to correctly delete and then increment the new one

Upvotes: 0

Views: 1126

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

To know the list of fields for a document you need to fetch it with the get() method, see https://firebase.google.com/docs/firestore/query-data/get-data and https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#get

For example:

let cityRef = db.collection('cities').doc('BJ');

cityRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

In the code above, doc is a DocumentSnapshot and if you call the data() method it will return "all fields in the document as an Object."

You just have to loop over the Object returned by the data() method to get the value X of the key(X) field, then increment it and write a new field key(X+1) with, for example, the update() method.


Note that, depending on your exact requirement, you may have to use a Transaction.

Upvotes: 2

Related Questions