I'm trying to implement a beforeSave function on cloud code and the following simple function doesn't work when there are multiple hashtags. Given if Product has two hashtags and the Hashtag table is empty, the following parse cloud code stores the second hashtag twice with a count of 1:
Parse.Cloud.beforeSave("Product", function(req, res) {
var product = req.object;
var hashtags = product.get("hashtags");
for (var i = 0; i < hashtags.length; i++) {
var currentHashtag = hashtags[i].toLowerCase();
var hashtagQuery = new Parse.Query("Hashtag")
hashtagQuery.equalTo("label", currentHashtag);
hashtagQuery.find({
success: function(results) {
if (results.length == 0) {
var hashtagClass = Parse.Object.extend("Hashtag");
var newHashtag = new hashtagClass();
newHashtag.set("label", currentHashtag);
newHashtag.set("count", 1);
newHashtag.save();
} else {
var hashtagObj = results[0];
hashtagObj.increment("count");
hashtagObj.save();
}
if (i == hashtags.length - 1)
res.sucesss();
},
error: function() {
res.error("Oops");
}
});
}
});
Aucun commentaire:
Enregistrer un commentaire