Reputation: 21478
I have Post
s and Topic
s on Parse. There are ~20 different Topic
s - each Post
stores up to 5 of them in an array relationship.
When a Post
is updated, I need to check the Topic
s it's assigned to and potentially send out notifications.
So I wrote this:
Parse.Cloud.afterSave("Post", function(request) {
Parse.Cloud.useMasterKey();
var postObject = request.object;
var postTitle = postObject.get("title");
var topics = postObject.get("topic");
var topicCount = topics.length;
console.log("Post with title " + postTitle + " has " + topicCount + " topics: " + topics);
// code continues to push logic,
// but already the log above is wrong, so I'll leave that off.
}
For example, if I make a post with a title of "Porsche Takes Aim at Tesla" and give it a single topic, the one for "tech", I would expect it to log something like:
Post with title Porsche Takes Aim at Tesla has 1 topics: tech
But instead when I do this, it logs:
Post with title Porsche Takes Aim at Tesla has undefined topics: [object Object]
What am I doing wrong? The documentation suggests that when you call get
with the name of an array field, it should return a JavaScript array. Instead it seems to be returning a blank JavaScript object without any attributes or contents at all.
I just need some way of seeing which topics are attached and iterating through them.
Note that I know this object is being created properly because I can see it in the data browser just fine. Navigating to the Post
and then clicking on View Relationship
under topic
shows me that it's properly connected to the tech
topic.
Upvotes: 0
Views: 75
Reputation: 1406
First: [object Object]
doesn't mean that object is empty. Use JSON.stringify()
to see it's contents.
As I understand topic is an object. In this case you shouldn't expect it to be printed as "tech". I guess you meant some property of this topic, like "name".
There may be also problem with setting the topic. Make sure to always use something like postObject.set("topic", arrayWithTopicsInside)
because I think that you have set this to topic that is not in an array. You may need to remove that column so it can be added with different type.
I think it should look like this:
Parse.Cloud.afterSave("Post", function(request) {
Parse.Cloud.useMasterKey();
var postObject = request.object;
var postTitle = postObject.get("title");
var topics = postObject.get("topic");
Parse.Object.fetchAll(topic).then(function(topics) {
var topicNames = []
_.each(topics, function(topic) {
var name = topic.get("name");
names.push(name);
});
console.log("Post with title " + postTitle + " has " + topicNames.count + " topics: " + topicNames);
}, function(error) {
concole.log("error fetching objects" + JSON.stringify(error));
});
}
Upvotes: 2