Ghobs
Ghobs

Reputation: 859

How to update a property of an object using Parse Cloud Code?

Every Parse Installation object instance in my Parse database has a pointer to a specific user. I have a background job that runs for every user, and what I want to do in this part of the background job is to set the respective user Installation's channel property to ["yesPush"], for push notification targeting purposes.

The way I figured I would do it is by querying for the specific Parse.Installation instance, and then setting its channels property. This doesn't seem to be working however. I'm trying to follow the guidelines in the Parse Cloud Code Docs, but it's either not the correct use case, or I'm not following it correctly.

Code:

var installationQuery = new Parse.Query(Parse.Installation);
installationQuery.equalTo('userId', parentUser);

installationQuery.find().then(function(results) {
  return Parse.Object.set('channels', ["yesPush"]);
});

Upvotes: 0

Views: 1512

Answers (1)

Timothy Walters
Timothy Walters

Reputation: 16874

The way I would do it is as follows:

// for every User
var userQuery = new Parse.Query(Parse.User);
userQuery.each(function(user) {
  var installationQuery = new Parse.Query(Parse.Installation);
  installationQuery.equalTo('userId', user);

  return installationQuery.first().then(function(installation) {
    installation.set('channels', ['yesPush']);
    return installation.save();
  });
}).then(function() {
  status.success();
}, function(error) {
  status.error(error.message);
});

The each() function is how you process large sets of data in a job. If you are performing other async tasks inside it you need to return their promise.

The first() function is much faster and easier if we only expect one record.

I am calling set() on the actual installation object returned by first().

I am returning the save() promise to allow promise chaining.

Upvotes: 2

Related Questions