这是我想要完成的事情:我有2个数据表 - 诗歌和搜索。每次用户将新记录保存到Poems表中时,我想检查它是否与已在搜索表中输入的任何搜索匹配。搜索数据表每个记录有3个字段:searchWordOne,searchWordTwo和searchWordThree。因此,每次在Poems表中创建一个新条目时,我想检查该条目的内容字段(这是一个字符串)是否包含searchWordOne,searchWordTwo或searchWordThree,用于搜索数据表中的任何记录。当匹配时,我想将相应的Searches表记录的objectId添加到Array。我该怎么做呢?这是我的尝试:
Parse.Cloud.afterSave("Poems", function(request) {
var searches = Parse.Object.extend("Searches");
var query = new Parse.Query(searches);
query.find({
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);
}
});
});
答案 0 :(得分:2)
让我们从匹配搜索的更严峻问题开始......
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();
}
对于与保存的诗歌相匹配的搜索,OP有点不清楚。如果你想改变那首诗(比如通过添加匹配的搜索),那么你应该使用beforeSave
。这样,保存的诗歌的变化也会得到保存......
_ = require("underscore");
Parse.Cloud.beforeSave("Poems", function(request, response) {
var aPoem = request.object; // see below
searchesMatching(aPoem).then(function(searches) {
var ids = _.map(searches, function(search) { return search.id; });
// 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() {
response.success();
}, function(error) {
response.error(error);
});
});
我认为问题的一部分与如何获取被保存的诗有关。第一行解释了这一点:request.object
是要保存的对象。