Exception in callback of async function: TypeError: callback is not a function - meteor

I cant figure out why my insert query code located in server/main.js is causing this: TypeError: callback is not a function error message.
The following code is located at: server/main.js
var businessCard = [{PostedDate: moment().add(0, "days").format('MM/DD/YYYY'), sentBy: currentUserId, recipientName: recipientName }];
Next line is the insert query:
Messages.insert({businessCard: businessCard}, {multi:true});
When I run the code, no inserts into the Messages collection are carried out, neither do I get any error messages in the browser console,
however when I check the terminal I see the following error message:
When I comment out the insert query, the error message disappears, leading me to think there is something wrong in how I have written this insert code.
Kindly help me figure out what am doing wrong here.
Looking forward to your help

The error is because you use multi: true option, insert method does not have this option.

Related

Error using Meteor.loginWithPassword

I am using "meteor.loginWithPassword" in my website for logging in but in the matter of fact I always get the error : "Match failed".
I do not find the reason why?
I have the user I am testing in my Database. I read somewhere that it is because one of the fields are empty, but this is not the reason.
I don`t know what should I check?
Template.login.events({
'submit form': function(event){
event.preventDefault();
var username = $('[name=username]').val();
var password = $('[name=password]').val();
Meteor.loginWithPassword(username, password, function(error){
console.log(error);
});
}
});
How to understand the error
When you're getting a Match error that's ultimately from the 'meteor/check' library.
So what you want to solve is "what Match conditions does the Meteor.loginWithPassword method expect". This will tell you what argument values will be permitted at runtime.
To answer that question you can look here https://github.com/meteor/meteor/blob/devel/packages/accounts-password where the code that sets up that method is defined.
NOTE: code references from here on arbitrarily reference version 2.5.8 to keep line references. However you could search under the version your code is at in essentially the same place
More specifically you're interested in the check call here https://github.com/meteor/meteor/blob/release/METEOR%402.5.8/packages/accounts-password/password_server.js#L170,#L173.
Bonus Round
It's worth noting that even if you were crawling the source code and found where Meteor.loginWithPassword is defined here https://github.com/meteor/meteor/blob/release/METEOR%402.5.8/packages/accounts-password/password_client.js#L33 it wouldn't be super obvious that the method call there gets picked up by the handler here https://github.com/meteor/meteor/blob/release/METEOR%402.5.8/packages/accounts-password/password_server.js#L166.
As it turns out the handlers match on the shape of arguments not the name 🙃.

Firebase -- no traceback or line number on error in Chrome

<script src="https://cdn.firebase.com/js/client/2.0.6/firebase.js"></script>
<script>
var root_ref = new Firebase('https://jcatest.firebaseio.com')
function other_function() {
// many lines of code here...
var x = {}
x.x()
// many lines of code here...
}
function my_function(snap){
other_function()
}
root_ref.once('value', my_function)
</script>
If I stick the above code in an html file and open it with Chrome all I see in the console is
"Uncaught TypeError: undefined is not a function ... firebase:26"
In Firefox I see the actual error message:
"TypeError: x.x is not a function ... temp.html:8"
Why am I not seeing the proper error message in Chrome?
Is this a Chrome bug? A Firebase bug? Or am I doing something wrong?
It's a big problem for me because there's a lot of code in my callback and firebase is basically saying, "there's an error somewhere." Not very helpful.
This problem was reproducible on FirebaseJS version 2.0.6. With Firebase 2.2.2, errors and full stacktraces are reported correctly on both browsers.
In the Firebase web client, the Firebase.DataSnapshot object has no method value(), but there is a val() method, which is probably what you're looking for.
See the DataSnapshot docs for more information.
I suspect that the browser is not giving you the relevant error line because the error occurs in an anonymous function, but that's a guess.
If you wrap the callback in a zero ms setTimeout call you get the traceback. Not sure why this is necessary.
root_ref.once('value', function(){ setTimeout(my_function) })

Meteor: Match error: Failed Match.OneOf or Match.Optional validation (websocket)

I have a website that uses Meteor 0.9. I have deployed this website on OpenShift (http://www.truthpecker.com).
The problem I'm experiencing is that when I go to a path on my site (/discover), then sometimes (though not always), the data needed are not fetched by Meteor. Instead I get the following errors:
On the client side:
WebSocket connection to 'ws://www.truthpecker.com/sockjs/796/3tfowlag/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
And on the server side:
Exception from sub rD8cj6FGa6bpTDivh Error: Match error: Failed Match.OneOf or Match.Optional validation
at checkSubtree (packages/check/match.js:222)
at check (packages/check/match.js:21)
at _.extend._getFindOptions (packages/mongo-livedata/collection.js:216)
at _.extend.find (packages/mongo-livedata/collection.js:236)
at Meteor.publish.Activities.find.user [as _handler] (app/server/publications.js:41:19)
at maybeAuditArgumentChecks (packages/livedata/livedata_server.js:1492)
at _.extend._runHandler (packages/livedata/livedata_server.js:914)
at _.extend._startSubscription (packages/livedata/livedata_server.js:764)
at _.extend.protocol_handlers.sub (packages/livedata/livedata_server.js:577)
at packages/livedata/livedata_server.js:541
Sanitized and reported to the client as: Match failed [400]
Can anyone help me to eliminate this error and get the site working? I'd be very grateful!
Tony
P.S.: I never got this error using localhost.
EDIT:
The line causing the problem the problem is this (line 41):
return Activities.find({user: id}, {sort: {timeStamp: -1}, limit:40});
One document in the activities collection looks like this:
{
"user" : "ZJrgYm34rR92zg6z7",
"type" : "editArg",
"debId" : "wtziFDS4bB3CCkNLo",
"argId" : "YAnjh2Pu6QESzHQLH",
"timeStamp" : ISODate("2014-09-12T22:10:29.586Z"),
"_id" : "sEDDreehonp67haDg"
}
When I run the query done in line 41 in mongo shell, I get the following error:
error: { "$err" : "Unsupported projection option: timeStamp", "code" : 13097 }
I don't really why this is though. Can you help me there as well? Thank you.
Make sure that you are passing an integer to skip and limit. Use parseInt() if need be.
You have a document on your website that does not match your check validation.
The validation you have is in app/server/publications.js:41
So the attribute in question exists in some way like Match.optional(Match.oneOf(xx)) but the document's attribute is neither of the values in Match.oneOf
You would have to go through your documents for the collection causing this and remove or correct the attribute causing this to match your check statement.
Update for your updated question.
You're running Meteor commands in the meteor mongo/mongo shell. The error you get is unrelated to the problem in Meteor, to sort in the mongo shell you would do activities.find(..).sort(), instead of activities.find(.., { sort : {..}). This is unrelated to the issue
The issue is most-likely that your id is not actually a string. Its supposed to be sEDDreehonp67haDg for the document you're looking for. You might want to use the debugger to see what it actually is.
I don't think you can use limit in client-side find queries. Removing limit from my query solves the problem. If you're looking for pagination, then you can either manually roll your own by passing a parameter to your Activities publication so that the limit is added to the server-side query along with an offset. There is also this pagination package.

ydn-db: calling get() for the second time cause error

I read a value from database, then based on that value, I read a second one. Here is the code:
mydb.db.get("store1", 1)
.then(function(result1) {
// Assume result1 is needed here.
// This second get() will cause error.
return mydb.db.get("store2", 1);
})
.then(function(result2) {
// Assume result2 is needed here.
});
The problem is, the second get() will cause this error (copied from console output in Chrome):
Uncaught TypeError: Cannot call method 'push' of undefined (in deferred.js:397)
If I remove the return clause, no error produced but I cannot get the result2.
I am using ydn.db-isw-core-qry.js (production) v0.8.12 with source map, IndexedDB database on Chrome 33.0.1750.149, Windows.
Is there something wrong with my code? Please help.
Thank you.
Here is test http://dev.yathit.com/test/issue_107.html as you described. No error. Please show your code that cause your error.

How would you handle errors when using jQuery.ajax()?

When using jQuery's ajax method to submit form data, what is the best way to handle errors?
This is an example of what a call might look like:
$.ajax({
url: "userCreation.ashx",
data: { u:userName, p:password, e:email },
type: "POST",
beforeSend: function(){disableSubmitButton();},
complete: function(){enableSubmitButton();},
error: function(xhr, statusText, errorThrown){
// Work out what the error was and display the appropriate message
},
success: function(data){
displayUserCreatedMessage();
refreshUserList();
}
});
The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens.
My problem seems to be that by throwing an exception the ashx causes the statusText and errorThrown to be undefined.
I can get to the XMLHttpRequest.responseText which contains the HTML that makes up the standard .net error page.
I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages.
Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take?
How do you handle these situations?
For debugging, I usually just create an element (in the case below: <div id="error"></div>) on the page and write the XmlHttpRequest to it:
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#error").html(XMLHttpRequest.status + "\n<hr />" + XMLHttpRequest.responseText);
}
Then you can see the types of errors that are occurring and capture them correctly:
if (XMLHttpRequest.status === 404) // display some page not found error
if (XMLHttpRequest.status === 500) // display some server error
In your ashx, can you throw a new exception (e.g "Invalid User" etc.) and then just parse that out of the XMLHttpRequest.responseText? For me when I get an error the XMLHttpRequest.responseText isn't the standard Asp.Net error page, it's a JSON object containing the error like this:
{
"Message":"Index was out of range. Must be non-negative and less than the size of the collection.\r\n
Parameter name: index",
"StackTrace":" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\r\n
at etc...",
"ExceptionType":"System.ArgumentOutOfRangeException"
}
Edit: This could be because the function I'm calling is marked with these attributes:
<WebMethod()> _
<ScriptMethod()> _
Should I be throwing the errors in the
ashx, or should I be returning a
status code as part of the data
returned by the call to
userCreation.ashx, then using this to
decide what action to take? How do you
handle these situations?
Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially).
However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code.
Now I have a problem as to which answer to accept.
Further thought on the problem brings me to the conclusion that I was incorrectly throwing exceptions. Duplicate user names, email addresses etc are expected issues during a sign up process and are therefore not exceptions, but simply errors. In which case I probably shouldn't be throwing exceptions, but returning error codes.
Which leads me to think that irobinson's approach should be the one to take in this case, especially since the form is only a small part of the UI being displayed. I have now implemented this solution and I am returning xml containing a status and an optional message that is to be displayed. I can then use jQuery to parse it and take the appropriate action: -
success: function(data){
var created = $("result", data).attr("success");
if (created == "OK"){
resetNewUserForm();
listUsers('');
} else {
var errorMessage = $("result", data).attr("message");
$("#newUserErrorMessage").text(errorMessage).show();
}
enableNewUserForm();
}
However travis' answer is very detailed and would be perfect during debugging or if I wanted to display an exception message to the user. I am definitely not receiving JSON back, so it is probably down to one of those attributes that travis has listed, as I don't have them in my code.
(I am going to accept irobinson's answer, but upvote travis' answer. It just feels strange to be accepting an answer that doesn't have the most votes.)

Resources