Skip to content

Instantly share code, notes, and snippets.

@alarner
Created October 14, 2015 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alarner/2a3f23a197df2bbb3b8a to your computer and use it in GitHub Desktop.
Save alarner/2a3f23a197df2bbb3b8a to your computer and use it in GitHub Desktop.
An example of using inner queries to filter data in Parse
Parse.initialize("honfjbWg6gddGuKOHokS5XaJCFMIW66nOV22138i", "EyOqRoG2xLM6UYHTV5LhehQgDuwjogYp86Il1umM");
var ProjectModel = Parse.Object.extend('Project');
var TaskModel = Parse.Object.extend('Task');
var UserModel = Parse.User;
// All tasks for a specific project
var projectId = 'xVwXfflkib';
var targetProjectModel = new ProjectModel({objectId: projectId, name: 'Nutella'});
var query = new Parse.Query(TaskModel); // Pass in model of things you want to get back
query.equalTo('projectId', targetProjectModel);
query.find().then(function(results) {
console.log(results);
});
// All tasks for a specific user
var userId = 'qXRvjks2O6';
var targetUserModel = new UserModel({objectId: userId});
var query = new Parse.Query(TaskModel); // Pass in model of things you want to get back
var innerQuery = new Parse.Query(ProjectModel);
innerQuery.equalTo('userId', targetUserModel);
query.matchesQuery('projectId', innerQuery);
query.include('projectId');
query.find().then(function(results) { // results coming back will be an array of tasks
// Group the results by their project id
// groupedResults will be an object with one property for each unique projectId.
// Each property will store an array of tasks
var groupedResults = _.groupBy(results, function(task) {
return task.get('projectId').id;
});
// Display the grouped results by iterating over each property in the object.
// i will be a string storing the name of the property in the object (in this case the projectId)
for(var i in groupedResults) {
console.log(i);
// groupedResults[i] will be an array of tasks
for(var j = 0; j<groupedResults[i].length; j++) {
// display each task in the array of tasks
console.log(' - '+ groupedResults[i][j].get('description'));
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment