GameScore
object have one Relation
field named Badges
.
How I can get count of all objects in this relation in query:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I need something like:
object.Badges.count
or
object.Badges.length
A Parse.Relation
object is actually a query description that will return the objects in that relation, so for this case you'd need to run another query for each GameScore
:
query.find().then(function (gameScores) {
alert("Successfully retrieved " + gameScores.length + " scores.");
var countPromises = gameScores.map(function (gs) {
// the following executes a count() query, which is severely penalized by Parse
return gs.get('Badges').query().count()
.then(function (count) {
// this extra step is to add the retrieved count as an extra property to the GameSccore object,
// instead of returning only the counts
gs.count = count;
return gs;
});
});
return Parse.Promise.when(countPromises);
}).then(function () {
var gameScoresWithBadgeCount = Array.prototype.slice.call(arguments);
}).fail(function(error) {
alert("Error: " + error.code + " " + error.message);
});
This causes a lot of extra round trips (I assume you're on a browser environment because of alert()
), and calls count()
queries which are additionally limited by Parse.
What I can recommend you is to keep a count cache as an extra field on the GameScore
class, and update it accordingly through CloudCode hooks. Alternatively, you can try to avoid the Relation
and make the equivalent using an Array field if possible, through which you can always include the related Badges if needed or get their count without querying for them at all!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments