Parse Cloud Code AfterSave Getting Saved Object

- 1 answer

Here's what I want to accomplish: I have 2 data tables - Poems and Searches. Every time the user saves a new record into the Poems table, I want to check if it matches any search that have been entered into the Searches table. The Searches data table has 3 fields per record: searchWordOne, searchWordTwo, and searchWordThree. So every time a new entry is made in the Poems table, I want to check if the content field (which is a string) of that entry contains searchWordOne, searchWordTwo, or searchWordThree for any of the records in the Searches data table. When there is a match, I want to add the objectId of the corresponding Searches table record to an Array. How do I do this? Here is my attempt:

Parse.Cloud.afterSave("Poems", function(request) {
  var searches = Parse.Object.extend("Searches");
  var query = new Parse.Query(searches);
    success: function(results) {
      for (var i = 0; i < results.length; i++) {
        var object = results[i];
        var keywordOne = object.get('searchWordOne');
        var keywordTwo = object.get('searchWordTwo');
        var keywordThree = object.get('searchWordThree');

    // I don't know how to get the content field of the object that has just
    // been saved in the Poems data table. 

    error: function(error) {
      alert("Error: " + error.code + " " + error.message);



Lets start with the tougher problem of matching searches...

function searchesMatching(aPoem) {
    var content = aPoem.get("content");
    var words = content.split(" ");
    var query1 = new Parse.Query("Searches");
    query1.containedIn("searchWordOne", words);
    var query2 = new Parse.Query("Searches");
    query2.containedIn("searchWordTwo", words);
    var query3 = new Parse.Query("Searches");
    query3.containedIn("searchWordThree", words);
    return Parse.Query.or(query1, query2, query3).find();

The OP is a little unclear about what you wish to do with searches that match the poem being saved. If you want to alter that poem (say, by adding the matching searches to it), then you should use a beforeSave. That way, the change to the poem being saved will get saved, too...

_ = require("underscore");

Parse.Cloud.beforeSave("Poems", function(request, response) {
    var aPoem = request.object;  // see below
    searchesMatching(aPoem).then(function(searches) {
        var ids =, function(search) { return; });
        // I don't know the name of poem col that keeps the ids array
        // not even sure you have one... just guessing from the question
        // this would be easier if poems had an array of pointers rather than an array of ids, anyway...
        aPoem.set("poemArrayOfSearchIds" ids);  // change the attribute name to the real name
    }).then(function() {
    }, function(error) {

I think part of the question had to do with how to access the poem being saved. That's explained on the first line: request.object is the object being saved.