how to troubleshooting nodejs? - node.js

I have a weird problem and need to troubleshoot it.
In my web application, I used the request module to get data from database. However, the request function didn't go to the api route setting(all other requests work well). How could I trace it to find out where it is coming from?
The error message I got back is:
{
errors: {
'confirmed_by.id': {
message: 'Cast to ObjectID failed for value "ending" at path "confirmed_by.id"',
name: 'CastError',
stringValue: '"ending"',
kind: 'ObjectID',
value: 'ending',
path: 'confirmed_by.id',
reason: [Object],
},
},
_message: 'order validation failed',
message:
'order validation failed: confirmed_by.id: Cast to ObjectID failed for value "ending" at path "confirmed_by.id"',
name: 'ValidationError',
}
Does anyone have any idea about this? Thanks in advance!
Richard

This error occur when you are trying to create a _id for the mongoose model using _id: new ObjectId(someVal). Here, you must ensure that the someVal should be 24 character hexadecimal value. Otherwise, it will raise that error. If say, you have someVal as 18 characters then add some static characters like aabbcc which is 6 characters more to make it 24 characters and most importantly, all needs to be hexadecimal characters.

There are several ways to debug a node application based on what you need to do or what issues you are having.
If you are on a fairly recent node version (v6.3+), you can always start your app with --inspect or --inspect-brk which will enable you to inspect your node code using Chrome. More details at https://nodejs.org/api/debugger.html#debugger_advanced_usage. In the case you are in an older version you can try with node-inspector
Another very useful tool is a network inspector (is that the right name?) like CharlesProxy; with this, you can configure your node application to proxy any http requests (configuration depends on which library you might be using) and inspect the traffic going between your node app and the rest of the world.

Related

NodeJS - ExpressJS - Mongo - Count Number of Documents Based on a Filter

I'm trying to get a count of documents based on my search criteria. Basically, each user on the site creates a handful of documents and I record the username of the person with each document in the collection.
I want to get a count of documents that have the searched username in them. I'm assuming MongoDB would have a way of doing this (at least I'm hoping so). If not, then I guess I'd have to get all the records and manually count them within my express code? Which I hope I don't have to do because that will hurt performance as this website scales.
Here is the code of what I have currently.
payload = {Username: req.query.Username}
console.log(payload)
if (req.query.Username) {
dbo
.snapUpvotesMongo()
.countDocuments(payload,function(err, result) {
if (err) { throw err; }
else { res.send(result) }
})
}
Based on the console log there, I know that the payload is formatted as "{ Username: 'test' }"
When I copy it into MongoDB Compass and run it through the collection, it returns the expected results. So that part is correct.
But when I run the above code, I get the below error:
Successfully connected to MongoDB.
Server is running on port: 3050
src\routes\routes.js:303:24
node:_http_server:274
throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
^
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 7
at new NodeError (node:internal/errors:371:5)
at ServerResponse.writeHead (node:_http_server:274:11)
at ServerResponse.writeHead (C:\Users\Brandon\Documents\GitHub\be-api\node_modules\on-headers\index.js:44:26)
at ServerResponse.writeHead (C:\Users\Brandon\Documents\GitHub\be-api\node_modules\on-headers\index.js:44:26)
at ServerResponse._implicitHeader (node:_http_server:265:8)
at ServerResponse.end (node:_http_outgoing:871:10)
at ServerResponse.send (C:\Users\Brandon\Documents\GitHub\be-api\node_modules\express\lib\response.js:232:10)
at C:\Users\Brandon\Documents\GitHub\be-api\src\routes\routes.js:303:24
at C:\Users\Brandon\Documents\GitHub\be-api\node_modules\mongodb\lib\utils.js:371:9
at C:\Users\Brandon\Documents\GitHub\be-api\node_modules\mongodb\lib\operations\execute_operation.js:71:66 {
code: 'ERR_HTTP_INVALID_STATUS_CODE'
}
[nodemon] app crashed - waiting for file changes before starting...
I've tried using .count() instead of .countDocuments and that doesn't appear to work either. So I must be misunderstanding something as to why this isn't returning anything.
I've also tried using .filter(), and putting my payload in there, but when I do that, I get the error "filter is not a function", which I assume is happening because of .countDocuments (since different routes in the same file use .filter, so I know it at least exists LOL)
I couldn't find much useful info to answer this when I looked around, so hoping someone else has ran into this before. (note that I am using Express-JS and to interface with MongoDB, I'm using the package "mongodb": "^4.9.0",
You're passing a number to res.send():
res.send(result)
Because it's a number, Express will interpret it as a HTTP status code and 7 (the number of matching documents) isn't valid (although I'm pretty sure that using res.send(Number, …) has been deprecated for a while now; I guess the Express developers have tried to maintain backward compatibility).
Instead, make sure you pass it as a string:
res.send(String(result))

Angular universal server error: When using the default fallback, a fallback language must be provided in the config

I have installed angular universal on my app.
Running npm run build:ssr - DONE. WORKS.
Running npm run server:ssr - DONE.WORKS.
After accessing the server URL (localhost:4000), the page is not fully loaded and the following error is raised on the Terminal:
I also faced the same problem, so I would just like to share my findings for the same.
For me, there were two plausible causes/solutions for it:
First, in my project's I18N default JSON file that was en.json, I was having a problem In the structure of the JSON file.
For example, I had the below mistake. I missed the comma after the second label 'FINISH' :
{
"COMMON": {
"EDIT": "Edit",
"FINISH": "Finish"
"QUIT": "Quit",
}
}
So after correcting the structure, the application ran fine without an error.
Secondly, another cause of the issue could be, at runtime transloco was not able to find the correct label in the selected language, so it looked for a fallback language and it could not even find that in the transloco-root.module.ts so after adding my fallback language, it tried to find the same in the fallback language as specified in the transloco-root.module.ts.
So it found out that label and the issue got resolved.
BUT in the second solution provided, you need to have that incorrect label in at least that fallback language's json file in correct format.
I added the fallback language like below:
useValue: translocoConfig({
availableLangs: ['fr', 'en'],
defaultLang: 'en',
reRenderOnLangChange: true,
fallbackLang: 'fr',
prodMode: environment.production,
missingHandler: {
logMissingKey: true
}
})
i18n Transloco wasn't fully configured on the module file.

Call from app to phone (web), app. with multi linked numbers

My use case is to be able to make a call from web interface to any number.
It all seams to work fine.
get jwt > login and get app. instance from ConversationClient > make a call using app.callPhone(number) > GET request to answer_url.
And this is where I stuck, it works if I will hardcode one of the linked numbers, like:
return [{
action: 'connect',
from: 'number',
endpoint: [{
type: 'phone',
number: query.to
}]
}]
but how I can pass query.from? or somehow decide on client side from which number I want to call?
Because each app can be linked to many numbers, and I don't want to create an app per number, but don't see any other solution.
I believe at the moment the client only supports sending a single string from the browser to the application, which you're using for to but as MrO hinted you can pass anything as an identifier here. I would suggest putting the to and from in the string separated by a comma eg: 12125551212,14155551000 and the splitting that in your answerUrl handler.

Dark mongoose magic: "Invalid argument to findOne"

We have several nodejs daemons that make use of mongoose while sharing the same persistence layer (shared module containing the queries).
In one of these daemons (always the same one) we randomly (few times a week) get the following error from mongoose:
mongoose: Invalid argument to findOne()
We've checked all queries and were not able to find out where this might come from. The errors call stack is different every time (no specific mongoose call seems to cause this issue) so we don't think this is specific to the business logic.
In order to do some debugging we added the following logging in case the error happens again:
log({
// What mongoose checks (both false -> the error).
isInstanceOfMQuery: conds instanceof mquery,
isObject: mquery.utils.isObject(conds),
// Trying to find out what this value is.
conds,
toString: Object.prototype.toString.call(conds)
inspect: util.inspect(conds, { showHidden: true, depth: null, showProxy: true })
})
conds is the argument that mongoose is complaining about. log() will JSON.stringify() the whole thing.
This is one of the logs that resulted from this call:
{
"isInstanceOfMQuery": false,
"isObject": false,
"conds": {},
"toString": "[object Null]"
"inspect": "{}",
}
Now this confuses me even more... how can conds be {} and null at the same time?!
Answers I'm looking for:
How can I reproduce this kind of object that conds contains?
How would you proceed with a bug that apparently happens randomly and seldomly?
Is there more we could log in order to identify what kind of value conds has or where it comes from?
Any ideas appreciated!
This is probably a node bug with the PR to fix here. It's not yet included in a release.
It's not reliably reproducible since it seems to depend on pointers and v8's garbage collection. Just gotta wait for it to be fixed upstream.

incorrect checksum for freed object

On POSTing data to my expressjs app, this is what I am getting:
node(58287,0x7fff771ad960) malloc: *** error for object 0x7ff8a8600c58: incorrect
checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
Any idea why?
Update:
Here is some code:
Client side:
$.ajax({
url: 'user/' + id,
type: 'POST',
dataType:'JSON',
data: JSON.stringify(data),
success: function(response){
console.log(response);
}
});
Server side:
app.post('/user/:id', function(req,res){
var id = req.params.id;
console.log(data);
});
When I use JSON.stringify on the client side, I am hitting this weird error:
node(58461,0x7fff771ad960) malloc: * error for object
0x7fa861d00e28: incorrect checksum for freed object - object was
probably modified after being freed.
* set a breakpoint in malloc_error_break to debug Abort trap: 6
When I don't use JSON.stringify on the client side, I get 'null' strings on the server side.
Any ideas on what I am doing wrong?
I experienced this same error recently. Here's the fix:
Node.js has had some bugs that cause it to install improperly from source under OS X (see e.g. issue 2061). The good news is that the packaged installer installs it correctly. So, simply uninstall Node, then head to http://nodejs.org/#download and run the Macintosh Installer.
I've reported this bug on the Node issue tracker here.
This is liable to be a bug in nodejs's internals. (Or, if expressjs has any native-code bindings, perhaps expressjs.)
There's no easy way for you to write this kind of bug yourself in JavaScript. If you can reproduce this at will, they'd probably like a bug report. Try to figure out the least amount of code that can reproduce the problem.
I just got this error today, and updating Node.js through MacPorts from 0.8.9_0 to 0.8.10_1 fixed the issue.
It doesn't seem this was specifically adressed though, as bug reports and the changelog don't indicate that (http://blog.nodejs.org/2012/09/25/node-v0-8-10-stable/).
I haven't looked into the cause of these issues (plural - there are clearly at least two bugs somewhere along the line - jquery, node, express), although a summary and workaround are as follows:
When your client side code looks like in your updated question the server obviously shouldn't crash with a malloc error (bug #1), although it is understandable that the query is mistreated, since you're telling jquery to send json and then you send a string.
bug #2 is simply null --> "null" along the pipe. This at least doesn't cause a server crash, because data types match headers (i.e. everyone think we're using json), however someone is converting nulls to strings. My baseless suspicion is that it's express/connect.
Finally, the workaround is simply to wrap your data in a way that manages to be transported, and then unwrap on the server side:
Client side:
$.post({
url: 'user/' + id,
data: {workaround: JSON.stringify(data)}, // no null strings this way
success: function(response){
console.log(response);
}
});
Server side:
app.post('/user/:id', function(req,res){
var id = req.params.id;
var data = JSON.parse(req.body.workaround); // unwrap
console.log(data);
});
If I find time, I'll investigate and try and post a bug report somewhere (it's a problem when you don't know whose fault this is...), please try do this as well.
You are are calling console.log server-side on 'data' which is not defined in the scope of your example.

Resources