MongoDB cursor.each throws error - javascript

I am trying to execute the following nodejs/mongoDB code:
var tickers = [];
MongoClient.connect(mongoUrl, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server."); //ok
var cursor = db.collection('STI').find();
cursor.each(function(err, doc){
assert.equal(err, null);
console.log(doc.symbol); //executes fine
tickers.push(doc.symbol);
})
});
console.log(tickers);
The symbols are logging out fine to the console but after that the code throws an error 'TypeError: Cannot read property 'symbol' of null'.
The code seems to forget the doc.symbol by the time it gets to executing the 'tickers.push' part. How do I fix this?
Update:
I tried shifting the console.log(tickers) into the cursor.each callback and it prints out the array which each iteration, so the symbol pushing is happening. however i still get the same error
Update: full error message
/Users/kevin/Projects/yahooscrape/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property 'symbol' of null
at /Users/kevin/Projects/yahooscrape/index.js:21:19
at handleCallback (/Users/kevin/Projects/yahooscrape/node_modules/mongodb/lib/utils.js:96:12)
at /Users/kevin/Projects/yahooscrape/node_modules/mongodb/lib/cursor.js:736:16
at handleCallback (/Users/kevin/Projects/yahooscrape/node_modules/mongodb/lib/utils.js:96:12)
at /Users/kevin/Projects/yahooscrape/node_modules/mongodb/lib/cursor.js:670:5
at handleCallback (/Users/kevin/Projects/yahooscrape/node_modules/mongodb-core/lib/cursor.js:154:5)
at setCursorDeadAndNotified (/Users/kevin/Projects/yahooscrape/node_modules/mongodb-core/lib/cursor.js:463:3)
at nextFunction (/Users/kevin/Projects/yahooscrape/node_modules/mongodb-core/lib/cursor.js:644:7)
at Cursor.next [as _next] (/Users/kevin/Projects/yahooscrape/node_modules/mongodb-core/lib/cursor.js:685:3)
at nextObject (/Users/kevin/Projects/yahooscrape/node_modules/mongodb/lib/cursor.js:655:8)

Use cursor.forEach() instead of cursor.each(). Cursor.forEach() is an officially implemented mongodb method that does not throw the errors shown in the question.

Related

nodeJS returns Type Error when creating a file using fs writeFile

I've just started learning nodeJS. I'm at a very basic level.
Right now I'm working with creating new files and directories methods.
This is my Code -
var fs = require('fs');
fs.mkdir("stuff", function () {
fs.readFile('readMe.txt', 'utf8', function (err, data){
fs.writeFile('./stuff/writeMe.txt', data);
});
});
It does create the directory and does read the file, but doesn't create a new file.
I checked the code times and again, but the terminal is returning this error.
fs.js:152
throw new ERR_INVALID_CALLBACK(cb);
^
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
[90m at maybeCallback (fs.js:152:9)[39m
[90m at Object.writeFile (fs.js:1351:14)[39m
at D:\PRANAV\Learning Folder\Node\app.js:6:12
[90m at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)[39m {
code: [32m'ERR_INVALID_CALLBACK'[39m
}
I'm stuck at this, please help.
fs.writeFile's last argument should be a callback function. Right now, you're missing it:
fs.mkdir("stuff", function () {
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('./stuff/writeMe.txt', data, function (err) {
if (err) {
throw err;
}
console.log('written successfully!');
});
});
});

How to get the exit code from a file ran using javascript child_process.execFile

Here is my python code:
#!/bin/python
import sys
sys.exit(4)
Here is my javascript
var exec = require('child_process').execFile
exec('./script.py', (err, data) => { if(err) { console.log(err.status) } })
But it doesn't work because there is not such thing as err.status
what I want to have in my console logs is '4'.
There isn't err.status, but there is err.code.
This should work:
var exec = require('child_process').execFile
exec('./script.py', (err, data) => { if(err) { console.log(err.code) } })
There is also err.signal and err.killed
From the nodejs docs:
On success, error will be null. On error, error will be an instance of
Error. The error.code property will be the exit code of the child
process while error.signal will be set to the signal that terminated
the process. Any exit code other than 0 is considered to be an error.
(https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback)
execFile's callback get 3 arguments:
error, if there was.
stdout, the stdout of process.
stderr, the stderr of the process.
So, by checking the stderr, you should be able to achieve the expected result:
var exec = require('child_process').execFile
exec('./script.py',(err,stdout,stderr)=>{console.log(stderr)})
See this in the Node.js docs

Error when run .js file with Node js "TypeError: Cannot read property 'render' of undefined"

I am writing a node program, but I meet an error when run following code (node test.js):
var pdf = require('html-pdf');
var options = {format: 'Letter'};
//console.log(" debug");
function Topdf(req,res) {
var info = require("./info.json");
res.render("./template.html",{ info : info,}, function (err, HTML) {
pdf.create(HTML, options).toFile('./downloads/employee.pdf', function (err, result) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
})
})
}
Topdf();
failed log:
res.render("./template.html",{ info : info,}, function (err, HTML) {
^
TypeError: Cannot read property 'render' of undefined
Could anyone please help? What is problem here?
Well, you are defining a function with 2 parameters (which should not start with a capital letter, BTW, since it is not a function to be called as a constructor), the second one being res
function Topdf (req, res) {
...
}
But you are invoking it with no arguments:
Topdf();
So req and res are undefined, so you cannot read the property render of undefined. The error message is quite explicit...

Dynamo DB getItem with node js throwing error

I am new to Javascript and DynamoDB. I am trying to perform getitem using aws-sdk for javascript in nodejs. primary index of Dynamo table Cars is "name" a string.
var AWS = require('aws-sdk');
AWS.config.region='eu-west-1';
var db = new AWS.DynamoDB();
var params = {
TableName : 'Cars',
Key : {
"name" : {
"S" : "Volkswagen Dasher"
},
}
}
db.getItem(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
}
else {
console.log(data); // successful response
}
return next();
});
On running the above .js file I am getting the following error.
ubuntu#ubuntu:~/node$ node getItem.js
{}
/home/ubuntu/node_modules/aws-sdk/lib/request.js:30
throw err;
^ ReferenceError: next is not defined
at Response.<anonymous> (/home/ubuntu/node/getItem.js:21:10)
at Request.<anonymous> (/home/ubuntu/node_modules/aws-sdk/lib/request.js:353:18)
at Request.callListeners (/home/ubuntu/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/home/ubuntu/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/home/ubuntu/node_modules/aws-sdk/lib/request.js:595:14)
at Request.transition (/home/ubuntu/node_modules/aws-sdk/lib/request.js:21:10)
at AcceptorStateMachine.runTo (/home/ubuntu/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /home/ubuntu/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/home/ubuntu/node_modules/aws-sdk/lib/request.js:37:9)
at Request.<anonymous> (/home/ubuntu/node_modules/aws-sdk/lib/request.js:597:12)
Plz help me out. Cheers!
Glad to see you're giving DynamoDB a try! I'm not really sure I understand the context of your code, but if your goal is to make a simple GetItem call, you don't need the 'return next()' statement. Given javascript's event driven nature, these callbacks are asynchronous and don't really "return" anything. Instead, you should inspect the response (data) and perform an action accordingly.
I.E.
dynamoDB.getItem(params, function(err, data) {
if (data) {
doSomethingWithItem(data.Item);
}
});
Also, if you're just starting out I would recommend taking a look at the document-js-sdk which a wrapper on top of the original SDK to allow you to use literals such as "string" instead of {S: "string"}.

When do you call db.close() when using cursor.forEach()?

If using .toArray(), I know you could use db.close() inside the callback like so:
db.collection('grades').find(query).toArray(function(err, docs) {
if (err) throw err;
console.dir(docs);
db.close();
});
But what if you need to iterate over the array? It seems excessive to 1) iterate through the cursor to construct the array and then 2) iterate over the array to do your work. So I was thinking that it'd be good to use cursor.forEach().
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {
if (err) throw err;
var cursor = db
.collection('data')
.find({})
.sort({State: 1, Temperature: -1});
var prevState = '';
var curr;
cursor.forEach(function(doc) {
if (doc.State === prevState) return;
db.collection('data').update(doc, { $set: { month_high: true}});
prevState = doc.State;
});
db.close();
});
However, this gives me an error:
~/code/m101js $ node test.js
/Users/azerner/code/node_modules/mongodb/lib/utils.js:97
process.nextTick(function() { throw err; });
^
TypeError: undefined is not a function
at /Users/azerner/code/node_modules/mongodb/lib/cursor.js:527:15
at handleCallback (/Users/azerner/code/node_modules/mongodb/lib/utils.js:95:12)
at /Users/azerner/code/node_modules/mongodb/lib/cursor.js:493:22
at handleCallback (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:234:5)
at /Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:533:22
at queryCallback (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:167:20)
at Callbacks.flush (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:86:7)
at Server.destroy (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:694:41)
at Server.close (/Users/azerner/code/node_modules/mongodb/lib/server.js:344:17)
at Db.close (/Users/azerner/code/node_modules/mongodb/lib/db.js:273:19)
~/code/m101js $ node test.js
/Users/azerner/code/node_modules/mongodb/lib/utils.js:97
process.nextTick(function() { throw err; });
^
TypeError: undefined is not a function
at /Users/azerner/code/node_modules/mongodb/lib/cursor.js:527:15
at handleCallback (/Users/azerner/code/node_modules/mongodb/lib/utils.js:95:12)
at /Users/azerner/code/node_modules/mongodb/lib/cursor.js:493:22
at handleCallback (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:234:5)
at /Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:533:22
at queryCallback (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:167:20)
at Callbacks.flush (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:86:7)
at Server.destroy (/Users/azerner/code/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:694:41)
at Server.close (/Users/azerner/code/node_modules/mongodb/lib/server.js:344:17)
at Db.close (/Users/azerner/code/node_modules/mongodb/lib/db.js:273:19)
~/code/m101js $
It seems to be all library code and I'm not really sure how to debug it. But it looks like the problem is in db.close().
Is this so?
If so, then where else would I put db.close()?
The issue is that db.close() was being called, and then I was trying to interact with the database. You can't interact with the database when the connection has already been closed.
The reason why my code was trying to interact with the database after the connection was closed is because the .update() is asynchronous.
Using async.each worked for me. async.each gives you a callback to run after everything in the collection has been iterated through. I called db.close() in that callback, which is the time when I wanted to close the connection to the database.

Categories

Resources