0

I iterate throught all the users node, I just want to send notifications to the users who have shop as a value inside the document, if there is users that dont have this attribute inside the document I dont want to send them a notification

exports.rememberToOpenStore = functions.pubsub.schedule('30 09 * * *').onRun(async (context) => {
    var db = admin.firestore();
    let snap = await db.collection('user').get();
                return snap.forEach((doc) => {
                    if(doc.data().shop !== null){
                        const deviceToken = doc.data().deviceToken
                        const payload = {
                        notification: {
                            title: "Good morning ! ",
                            body: "Remember to open your store."
                        }
                    }
                    return admin.messaging().sendToDevice(deviceToken,payload)
                    }
                    return null;
            });
});

I want to know if this

if(doc.data().shop !== null)

will do the trick to know which user has or not that attribute

Is there a better way to do this with a where query with something like

let snap = await db.collection('user').where("shop" "!=", null).get();

to just get users that have that shop value inside the document ?

I want to do it that way to save reads

SNM
  • 5,625
  • 9
  • 28
  • 77
  • Firestore does not provide any checks for inequality or field existence, so you can't avoid reading every document if you're just looking for fields that exist. The only way to do this efficiently is to make sure every document has a field value that you can filter on. A simple boolean will probably work here. – Doug Stevenson May 09 '20 at 22:26
  • You mean like, hasShop and filter for users that have shops with where("hasShops",true) ? that sounds great – SNM May 09 '20 at 22:28
  • Sure, you could try that. – Doug Stevenson May 09 '20 at 22:28
  • want to put this as an answer , I will upvote, thanks for the tip – SNM May 09 '20 at 22:29
  • I already marked this question as a duplicate. – Doug Stevenson May 09 '20 at 22:29
  • hey @DougStevenson , thanks a lot for this tip !! you prevented me to do like 1000 reads instead of just 13 , I'm doing so many things that I'm becoming an octopus haha, thanks – SNM May 09 '20 at 22:34

1 Answers1

1

if(doc.data().shop !== null)

If shop is undefined then your code won't catch the issue.

You can do something like

if(typeof doc.data().shop === 'string') // or whatever the type is, like boolean or number.

then you'll be sure that shop has a value.

  • Thanks a lot for you answer, but I have tried it and it does not work for me – SNM May 09 '20 at 22:29
  • You’re welcome! Using typeof is great for checking if an attribute is present. But say shop is supposed to be a Boolean, then you just do shop === true. – AnotherWombat42 May 10 '20 at 15:56