Meteor method giving error - javascript

I am new to Meteor. I am trying to call a Meteor.method('addTask') from an event helper and I keep getting the error: "Error invoking Method 'addTask': Method 'addTask' not found [404]". I will put my code below:
Template.add_task.events({
'submit .js-emoticon': function(event){
event.preventDefault();
// console.log('clicked');
// var text = event.target.text.value;
// $('#text_display').html(text);
// $('#text_display').emoticonize();
Meteor.call("addTask");
}
});
And the Meteor.method here:
Meteor.methods({
'addTask':function(){
var task = event.target.text.value;
Items.insert({
created:new Date().toLocaleDateString("en-US"),
task:task
});
console.log(task);
}
});
Both are on the main.js in the client folder. I have tried to put the method on the server/main.js and I get an error: "Error invoking Method 'addTask': Internal server error [500]".
If it is on the client it will log the value of #text to console but on the server it doesn't even do that.
As I said I have been learning Meteor and researched this as the way to do it. I am obviously missing something and can't figure it out. Any help would be appreciated.

You are trying to look at a DOM element from your server code. You need to get that element on the client and then pass it to the method, which you can put in the /lib folder for latency compensation if you wish.
Client:
Template.add_task.events({
'submit .js-emoticon': function(event){
event.preventDefault();
var task = event.target.text.value;
Meteor.call("addTask",task);
}
});
Server:
Meteor.methods({
'addTask':function(task){
check(task,String);
Items.insert({ created: new Date(), task: task });
console.log(task);
}
});
You never want to convert your dates to strings when you persist them in mongo. That makes searching on dates impossible.

Related

My meteor insert not working on with click event, but there is no error for me to debug

I have a click event that allows a user to insert data, or an object from one collection to another collection, the image bellow is the single object the user is capturing and inserting into the other collection.
This is the click event.
Template.postsView.events({
'click .rediscover-toggle': function(e){
var descovery = this;
console.log(descovery);
e.preventDefault();
Meteor.call('rediscovering', {descovery: descovery});
},
});
Everything here seems fine because that image is the console.log for the captured data, so when i click, i get that object in the console,
In my methods it looks like this
Meteor.methods({
rediscovering: function (descovery) {
RediscoveryCollection.insert(descovery);
}
})
So im trying to insert that object as it is into another collection but its not inserting and i'm not getting any errors in the chrome browser nor the server terminal
The most common cause of this problem is that you are not publishing and subscribing to the collection. The object ends up getting inserted - you can verify that using the $ meteor mongo console. Please make sure that you have the autopublish package installed or that you do:
server:
Meteor.publish('rdc',()={
return RediscoveryCollection.find();
});
client:
Meteor.subscribe('rdc');

MeteorJS I can't seem to ever get a property of an object from the server

Hey guys I have been having a ton of problems with meteorJS, because I can't seem to ever access the properties of anything client side when I subscribe to the publication on the server side. I have a collection with a "daily event" for my users that I'm going to be trying to publish to the client side. But for some reason it's undefined on the client side, even though I can do a console.log on the server side and it works fine.
Here's the code:
Client side:
communityEvents = new Mongo.Collection("communityEvents");
Meteor.subscribe('communityEventsPub');
Template.communityEvent.helpers({
type: function(){
todaysEvent = communityEvents.find().fetch();
console.log("this is the event " + todaysEvent["type"]);
return todaysEvent.type;
},
event: function(){
todaysEvent = communityEvents.find().fetch();
return todaysEvent.event;
}
});
Server Side:
communityEvents = new Mongo.Collection("communityEvents");
Meteor.publish("communityEventsPub", function(){
console.log(moment().format('l'));
console.log(communityEvents.find({date:moment().format('l')}).fetch());
return communityEvents.find({date:moment().format('l')});
});
fetch returns an array. In your helpers you'd need to do something like:
var todaysEvent = communityEvents.find().fetch()[0];
or
var todaysEvent = communityEvents.findOne();
You can easily test a publication by opening your browser console and doing a fetch like so:
communityEvents.find().fetch()
Which will return an array (hopefully) that you can examine.

Meteor - Server-side API call and insert into mongodb every minute

I am in the process of learning Meteor while at the same time experimenting with the TwitchTV API.
My goal right now is to call the TwitchAPI every minute and then insert part of the json object into the mongo database. Since MongoDB matches on _id and Twitch uses _id as its key I am hoping subsequent inserts will either update existing records or create a new one if the _id doesnt exist yet.
The call and insert (at least the initial one) seem to be working fine. However, I can't seem to get the Meteor.setTimeout() function to work. The call happens when I start the app but does not continue occurring every minute.
Here is what I have in a .js. file in my server folder:
Meteor.methods({
getStreams: function() {
this.unblock();
var url = 'https://api.twitch.tv/kraken/streams?limit=3';
return Meteor.http.get(url);
},
saveStreams: function() {
Meteor.call('getStreams', function(err, res) {
var data = res.data;
Test.insert(data);
}
}
});
Deps.autorun(function(){
Meteor.setTimeout(function(){Meteor.call('saveStreams');}, 1000);
});
Any help or advice is appreciated.
I made the changes mentioned by #richsilv and #saimeunt and it worked. Resulting code:
Meteor.startup(function(){
Meteor.setInterval(function(){Meteor.call('saveStreams');}, 1000);
});

Need to run code on save and log from Parse Cloud Code when updating PFObject's key in iOS app

I have a PFObject that has an array key. I can successfully call addObject: on this PFObject, and can confirm that the object has been added to the array key properly using an NSLog. However, when I try to save the PFObject to Parse, even though it says everything went successful, the changes are not shown in the Data Browser.
I have tried everything, and can even get this to work in an older version of my app, but for some reason it will not work anymore.
I posted another StackOverflow question about this here
The only response I got were some comments saying that I should trigger a "before save" function and log everything via Cloud Code. The problem is I don't know javascript, and I've been messing around with Cloud Code and nothing's happening.
Here is the code I am executing in my app:
[self.message addObject:currentUsersObjectId forKey:#"myArrayKey"];
And then I am using saveInBackgroundWithBlock:
I need to alter Cloud Code so that it will check the self.message object's "myArrayKey" before saving and log the results.
Edit 2:
Here is how I create currentUsersObjectId:
NSString *currentUsersObjectId = [[NSString alloc]init];
PFUser *user = [PFUser currentUser];
currentUsersObjectId = user.objectId;
Edit 3:
Here is the save block
[self.message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(#"An error has occurred.");
}
}];
Edit 4:
After adding Timothy's cloud code, the saveInBackgroundWithBlock: now does not successfully complete. Instead an error occurs, and the error object NSLogs as `"Error: Uncaught Tried to save an object with a pointer to a new, unsaved object. (Code: 141, Version: 1.2.17)" and also as:
Error Domain=Parse Code=141 "The operation couldn’t be completed. (Parse error 141.)" UserInfo=0x15dc4550 {code=141, error=Uncaught Tried to save an object with a pointer to a new, unsaved object.} {
code = 141;
error = "Uncaught Tried to save an object with a pointer to a new, unsaved object.";
}
Here is my complete Cloud Code file after adding Timothy's code:
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId;
//newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
var currentUser = request.user;
var relation = user.relation("friendsRelation");
relation.add(currentUser);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
Parse.Cloud.beforeSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saving message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
// log the after-save too, to confirm it was saved
Parse.Cloud.afterSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saved message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
After much back and forth, I'm stumped as to why this isn't working for you. As for logging in Cloud Code, if you follow the guide on adding code you can add the following to your main.js and deploy it:
Parse.Cloud.beforeSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saving message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
// log the after-save too, to confirm it was saved
Parse.Cloud.afterSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saved message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
With those in place you have plenty of server-side logging that you can check.
I am adding my own answer in addition to Timothy's in case anyone else is having a problem similar to this. My app uses the following library to allow parse objects to be stored using NSUserDefaults: https://github.com/eladb/Parse-NSCoding
For whatever reason, after unarchiving the parse objects, they are not able to be saved properly to the Parse database. I had to query the database using the unarchived one's objectId and retrieve a fresh version of the object, and then I was able to successfully make changes to and save the retrieved object.
I have no idea why this is happening now. I have never had any problems until about two weeks ago when I tried to deploy a new version of my cloud code, and if I remember correctly, Parse wanted me to update the Parse SDK or the Cloud Code version before I could deploy it.
These changes must not be compatible with these categories.

Using Node and Socket.io I am trying to pass a simple array and I'm getting nothing. What did I miss?

I followed the net tuts tutorial to build a simple chat application with socket and node, and now I'm trying to extend the app to allow people to play a game I've written, so I want to let people list the games available, but I can't seem to pass even a simple test array from server to client.
I'll let the code speak for itself:
Relevant Server Code:
var games = ["test"];
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('gameList', function (data) {
io.sockets.emit("games",games);
});
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
ClientSide:
window.games = [];
$("#listGames").click(function(){
socket.emit("gameList", function(data){
window.games = data;
})
})
So I console.log games before and after the button click, and it's always just an empty array, when in my head, it should contain the string "test".
So where did I go wrong?
Note:
Added jQuery to the codebase even though the tutorial missed it.
You are using socket.emit() to attempt to receive data. That only sends data to the server. You need a games event handler on your client to handle the event accordingly.
window.games = [];
$("#listGames").click(function() {
socket.emit('gameList');
});
socket.on('games', function (games) {
window.games = games;
});
The event handler for games is what will fire when you execute io.sockets.emit('games', games); on the server side.
Also make sure to always pass an object as the response over Socket.IO. Change the server-side code from : var games=[]; to var games={'games':[]}; or something similar.

Categories