'process.nextTick(function() { throw err; })' - Undefined is not a function (mongodb/mongoose) - node.js

I'm trying to connect to my mongodb using nodejs and socket.io. I am able to connect to the database because I get 'connection accepted' in my console but on the nodejs side, as soon as I - indeed - get
Connection to mongodb://localhost:27017 established through mongoose
it immediately fails next with
process.nextTick(function() { throw err; }) ^TypeError: undefined is
not a function at showCollections**
And here goes showCollections:
var showCollections = function(db, callback) {
mongoose.connection.db.collectionNames(function(error, names) {
if (error) {
throw new Error(error);
} else {
console.log("=>Listening mongo collections:");
names.map(function(cname) {
mongoose.connection.db.dropCollection(cname.name);
console.log("--ยป"+cname.name);
});
}
});
}
And here is the content of my database folder:
_tmp (empty folder)
local.0
local.ns
mongod.lock
I run the mongodb by typing mongod --dbpath folder and it successfully 'awaits connections on port 27017'.
Also, my node_modules from package.json (npm)
"dependencies": {
"express": "^4.9.6",
"socket.io": "latest",
"mongodb": "~2.0",
"mongoose": "*"
}
Thank you very much for your help...
StackTrace:
> TypeError: undefined is not a function
> at showCollections (/usr/share/nginx/www/index.js:77:25)
> at NativeConnection.callback (/usr/share/nginx/www/index.js:46:3)
> at NativeConnection.g (events.js:199:16)
> at NativeConnection.emit (events.js:104:17)
> at open (/usr/share/nginx/www/node_modules/mongoose/lib/connection.js:485:10)
> at NativeConnection.Connection.onOpen (/usr/share/nginx/www/node_modules/mongoose/lib/connection.js:494:5)
> at /usr/share/nginx/www/node_modules/mongoose/lib/connection.js:453:10
> at /usr/share/nginx/www/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:59:5
> at /usr/share/nginx/www/node_modules/mongoose/node_modules/mongodb/lib/db.js:200:5
> at connectHandler (/usr/share/nginx/www/node_modules/mongoose/node_modules/mongodb/lib/server.js:272:7)
EDIT:
I'm as well having these problems when trying to run the nodejs instance:
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
I tried fixing them as other questions here would tell but nothing worked either...

From the provided information, it looks like you are using mongodb 2.0 driver. The db.collectionNames method was dropped. Check out the "Db Object" section of this page - https://github.com/mongodb/node-mongodb-native/blob/0642f18fd85037522acf2e7560148a8bc5429a8a/docs/content/tutorials/changes-from-1.0.md#L38
They've replaced it with listCollections. You should get the same effect with:
mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});

For me this error started popping up when i had to force shut down my pc as it became unresponsive. Next time i started my express server this error popped up. I solved it by running npm install mongoose#4.0 --save in the terminal.
May be this error pops up when your server or database is force closed and some code is not save in mongod behind the scenes.

Shouldn't you specify the full path and have an export module?...something like:
mongoose.connection.db.collectionNames(function (err, names)
{
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
}
If I'm wrong it's because I don't fancy moongodb :)

Related

Random occurrences of Failed: ECONNREFUSED connect ECONNREFUSED 127.0.0.1 when running protractor tests

My protractor test cases randomly fail with this error message:
Failed: ECONNREFUSED connect ECONNREFUSED 127.0.0.1
I have gone through the resources and tried all the suggested solutions:
Upgraded protractor
Ran webdriver-manager update
Upgraded chromedriver version but the issue seems to exist.
This particularly happens when I try to run all the e2e tests together.
Below is the specific versions that Im using for my project:
node - v9.2.0
protractor - Version 5.4.1
ChromeDriver 2.42.591088
Please help.
Thanks,
Neeraja
Are you using async/await in your tests?
Can you try applying patch as specified below from the same folder which contains the 'node_modules' folder by executing 'node patch.js'?
patch.js file
var fs = require('fs');
var httpIndexFile = 'node_modules/selenium-webdriver/http/index.js';
fs.readFile(httpIndexFile, 'utf8', function (err, data) {
if (err)
throw err;
var result = data.replace(/\(e.code === 'ECONNRESET'\)/g, "(e.code === 'ECONNRESET' || e.code === 'ECONNREFUSED')");
console.log(`Patching ${httpIndexFile}`)
fs.writeFileSync(httpIndexFile, result, 'utf8');});
var chromeFile = 'node_modules/selenium-webdriver/chrome.js';
fs.readFile(chromeFile, 'utf8', function (err, data) {
if (err)
throw err;
var result = data.replace(/new http.HttpClient\(url\)/g, "new http.HttpClient(url, new (require('http').Agent)({ keepAlive: true }))");
console.log(`Patching ${chromeFile}`)
fs.writeFileSync(chromeFile, result, 'utf8');});
Please see original post here -
https://github.com/angular/protractor/issues/4706#issuecomment-393004887

EPIPE write error html-pdf only on appfog server

I'm having a very weird EPIPE write error when I'm trying to generate a PDF from HTML with this module:
https://www.npmjs.com/package/html-pdf
The exact error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
The line where I call the PDF gen:
var pdfgen = require("html-pdf");
pdfgen.create(html, options).toFile('whappbook.pdf', function(err, res) {
var errorCount = 0;
if (err) {
console.log(err);
errorCount++;
if(errorCount > 2) {
return console.log(err);
} else {
return create();
}
}
console.log(res); // { filename: '/app/businesscard.pdf' }
});
I've tried just using <h1>Testing</h1> as the HTML to see if the file was too big, but that wasn't the case.
Note: local everything works perfectly fine, but when I run this code on Appfog it doesn't work, so I suspect it has something to do with missing dependencies or file writing rights.
I'm writing directly to the home directory (in Appfog's case thats /app).
HTML-PDF is using PhantomJS and I've also directly npm'd that in my app because some people were reporting issues when it wasn't directly installed, but that didn't solve my problem either.
If there is any information that I can additionally provide please let me know!

zombiejs (2.0.0-alpha30) + mochajs (1.17.1) on node 0.10.26

I started working through a book's example code and had the bright idea to update the libraries (node included, from 0.8 -> 0.10). Now there is some breakage & I get this error:
1) Todos Todo creation form should allow to create a todo:
Uncaught Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
I've commented out the assertions to try and locate the issue. It seems like it's a zombiejs centric issue but I'm not sure how to verify that because there are many modules installed as dependencies. There are 10 other tests that pass with most using the login function so I eliminated that from the probabilities. I tried to just post the necessary code snippets. I can provide more if this isn't enough detail. I've found a few stackoverflow posts with this error but the solutions didn't apply. If it turns out to be a zombie issue I will post something on their bug site.
it('should allow to create a todo', login(function (browser, done) {
Browser.visit('http:localhost:3000/todos/new', function (err) {
if (err) throw err;
//browser
// .fill('textarea[name="what]', 'Test todo')
// .pressButton('input[type="submit"]', function (err) {
// if (err) throw err;
//browser.assert.pathname('/todos', 'should be redirected to /todos');
//finish assertions
//browser.assert.elements('#todo-list tr.todo', 1, 'To-Do list should contain 1 item');
//});
});
}));
The main entries in package.json:
"dependencies": {
"union": "0.4.0",
"flatiron": "0.3.x",
"plates": "0.4.x",
"node-static": "0.7.x",
"nano":"5.x.x",
"flatware-cookie-parser" : "0.1.x" ,
"flatware-session": "0.1.x"
},
"devDependencies": {
"mocha" : "latest",
"zombie": "latest"
},
Thanks!!!
Ah, it was a stupid user error. I forgot to tell mocha the test was "done();". I added done to the end of the test case...tests are working as expected. Thanks!

Node JS Error: Cannot find module './build/Release/mysql_bindings'

I have installed Node.Js and Casper.js to perform webscraping and save the info into a DB. But I have a problem because when I try to execute the source, I get the following error in the terminal:
Error: Cannot find module './build/Release/mysql_bindings'
I have previously installed mysql-libmysqlclient with the mysql_bindings inside. I tested creating the route of the error, but it didn't work.
The code is:
var mysql = require('db-mysql');
new mysql.Database({
hostname: 'localhost',
user: 'rool',
password: 'xxxx',
database: 'xxxBD' }).connect(function(error) {
if (error) {
return console.log('CONNECTION error: ' + error);
}
this.query().
select('*').
from('tablaPruebas').
execute(function(error, rows, cols) {
if (error) {
console.log('ERROR: ' + error);
return;
}
console.log(rows.length + ' ROWS found');
});
});
Thanks in advance!
The problem is that your using the following in your code:
var mysql = require('db-mysql');
However your question shows that you have installed mysql-libmysqlclient. This means you should be using the following instead:
var mysql = require('mysql-libmysqlclient');
I presume you installed from https://github.com/Sannis/node-mysql-libmysqlclient
The code you're using looks more like db-mysql which can be found here
If you install via npm install db-mysql then you should be good. Have a look at the link I included for db-mysql as there appears to be a few dependencies (e.g. setting up MYSQL_CONFIG environment variable).

node.js + express error: cannot read property 'url' of undefined

I'm fairly new to Node.js, installing it to try out the DrupalChat (v7dev) module. I believe this problem is with either node.js or express, as I am beyond the stage where the chat module's settings are loaded. I am faced with the following output when trying to start the chat server
Extension loaded: drupalchat_nodejs.server.extension.js
Started http server.
info - socket.io started
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'url' of undefined
at Function.handle (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/proto.js:105:18)
at Server.app (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/connect.js:60:31)
at Server.serverListening (/usr/local/lib/node_modules/npm/node_modules/socket.io/node_modules/policyfile/lib/server.js:136:16)
at Server.g (events.js:154:14)
at Server.emit (events.js:64:17)
at Array.1 (net.js:710:10)
at EventEmitter._tickCallback (node.js:192:40)
I remember when express installed, it gave a warning like ".... bugs['web'] should probably be bugs['url']" (I can't remember the prefix)
So is it that the server is trying to read an (API?) variable 'url' but its currently 'web'?
I have all the modules up to date, is it that I should downgrade? Or is there some way of working around this using another module?
EDIT:
line 201 is the last very line (delete authenticatedClients[authData.authToken];)... I just added to whole function for proper context
var authenticateClientCallback = function (error, response, body) {
if (error) {
console.log("Error with authenticate client request:", error);
return;
}
if (response.statusCode == 404) {
if (settings.debug) {
console.log('Backend authentication url not found, full response info:', response);
}
else {
console.log('Backend authentication url not found.');
}
return;
}
var authData = false;
try {
authData = JSON.parse(body);
}
catch (exception) {
console.log('Failed to parse authentication message:', exception);
if (settings.debug) {
console.log('Failed message string: ' + body);
}
return;
}
if (!checkServiceKey(authData.serviceKey)) {
console.log('Invalid service key "', authData.serviceKey, '"');
return;
}
if (authData.nodejsValidAuthToken) {
if (settings.debug) {
console.log('Valid login for uid "', authData.uid, '"');
}
setupClientConnection(authData.clientId, authData, authData.contentTokens);
authenticatedClients[authData.authToken] = authData;
}
else {
console.log('Invalid login for uid "', authData.uid, '"');
delete authenticatedClients[authData.authToken];
}
}
Per #thesnufkin's post, looks like the underlying express version currently pulled is not stable. Roll back to 2.5.9 and you should be good to go:
npm uninstall express
npm install express#2.5.9
As requested,
The v7 chat module from drupal is not stable. You should not use it in production.
Check bugs : http://drupal.org/project/issues/drupalchat?status=All&categories=All
Check forums : http://drupalchat7.botskool.co.in/?q=forum
Still looking for a new maintener:
"New maintainer wanted - please ping beejeebus if you're interested!".
nodejs module has this issue, so I don't think its related to the drupalchat server specifically. Here is the issue for that: http://drupal.org/node/1537702
The option to use node.js as backend in DrupalChat is currently under development. It also depends when (date on which) you downloaded the DrupalChat since the dev code is updated everyday, if new code is committed.
Please raise an issue for the same at this link - http://drupal.org/project/issues/drupalchat?status=All&categories=All.
Thanks,
darklrd

Resources