mark dean Raymundo
mark dean Raymundo

Reputation: 55

How to check if firestore document have a particular field

I have a cloud function that gets all docs in the collection. After getting all docs, i need to check if a field lets say 'link' exist in each document. If the document do not have the 'link' field i will update that document with the link. btw the 'link' is recently added so some of the docs have it and some do not have it. Is there a way to check if the field is already in the document?

const taskCol = await firestore.collection('/tasks/').get();

taskCol.forEach(task=>{
    const taskData = task.data();

    //check if field is existing. 
    if(taskData.link == null){ //THIS PART IS NOT WORKING
    //i tried taskData.get('link') == null -->not working
   //i tried taskData.link.exist() == true -->not working either


    //create  link
    taskData.dynamicLink = createLink();

    //update the task doc here
    /*my update task code is here*/
    }


});

Upvotes: 3

Views: 2237

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

The following would do the trick:

taskCol.forEach(task => {
    const taskData = task.data();

    //check if field is existing. 
    if (taskData.link)  {
          ....
    }

    ...
});

Actually, the data() method returns a "standard" JavaScript object (or undefined).

Upvotes: 3

Related Questions