Add an element to an array field in User class from cloud code

i’m trying to add an element to an array field called notifications in User class from a cloud code functions triggered when a notifications is created
i fetch a list of users i’m trying to add the notif for like this
that’s the code

for(const parseuser of userqueryresults) {
            console.log("user id that we save notif for is "+parseuser.id);
            parseuser.addUnique("notifications",notification.id);
            parseuser.save(null,{useMasterKey:true});
            
          }

but nothing is happening please help

Hi @BendabizAdam, thanks for posting.

A couple of questions:

-does the console.log statement get called?
-is user query results.length greater than 0?
-do you have any beforeSave trigger on the user class that would strip out “notifications”, or prevent the save of the user

I would also recommend:

-Adding parse user to an array and using await Parse.Object.saveAll
-using pointers on “notifications” (if you’re planning to send a lot of notifications, the array could get quite long)

If you send your full cloud function including the query, that might help :blush:

hi there thanks for your reply …
yes the log does happen with user’s id
length is greater than 0
i have no beforesave trigger on user’s class
i’m a bit new to parse so i didn’t get ur recommendations if u may please explain more
thanks in advance

i got it working just by adding .then after save … this is stupid

So I would recommend:

Parse.Cloud.define('SendNotification', async (req) => {
  const userQuery = new Parse.Query(Parse.User);
  userQuery.equalTo(...);
  const users = await userQuery.find({useMasterKey:true});
  const usersToSave = [];
  for (const parseuser of users) {
    parseUser.addUnique('notifications', notification.id);
    usersToSave.push(usersToSave);
  }
  await Parse.Object.saveAll(usersToSave,{useMasterKey:true});
  return 'Notifications have been saved.';
});
1 Like