Can't connect Mongodb to Node.js, MEAN-stack - javascript

I'm a Mac user and I'm very new to MEAN-stack. I'm trying to connect a Mongoose with my Node.js but it always show this error
events.js:141
throw er; // Unhandled 'error' event
^
Error: failed to connect to [undefined:27017]
at null.<anonymous> (/Users/toeysk/Desktop/testwebrtc.git/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:556:25)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (/Users/toeysk/Desktop/testwebrtc.git/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:156:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/Users/toeysk/Desktop/testwebrtc.git/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:534:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at connectErrorNT (net.js:996:8)
at doNTCallback2 (node.js:452:9)
at process._tickCallback (node.js:366:17)
I can use both Mongoose and Mongodb normally in my terminal.
Here is my server.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var mongoose = require('./config/mongoose'); //connect DB
var express = require('./config/express');
var db = mongoose();
var app = express();
app.listen(3000);
module.exports = function(){
require('../app/routes/index.routes')(app);
require('../app/routes/user.routes')(app);
};
module.exports = app;
And it calls mongoose.js
var config = require('./config');
var mongoose = require('mongoose');
console.log('Mongoose.js');
console.log(config);
module.exports = function(){
mongoose.set('debug', config.debug);
var db = mongoose.connect(config.monoUri);
console.log('Call User Model');
require('../app/models/user.model');
return db;
};
Then calls config.js and development.js
/////config.js/////
module.exports = require('./env/' + process.env.NODE_ENV + '.js');
/////development.js/////
module.exports = {
debug: true,
mongoUri: 'mongodb://localhost/webrtc',
sessionSecret: 'dev_secret_key'
};
Please help. I have been trying to debug this about 2 days and I got nothing new. Anything miss?

The error is pointing you towards the issue:
Error: failed to connect to [undefined:27017]
So there's something wrong with the location of the database, it looks like the hostname is undefined.
Here's your connection code:
var db = mongoose.connect(config.monoUri);
And here your configuration:
mongoUri: 'mongodb://localhost/webrtc'
Can you spot the typo in your connection code? It says monoUri, not mongoUri.

can you do
npm install mongoose
and also post the output from
ps -ef | grep mongod
All on the the machine you are running node from. That would go a long way towards the rest of an answer.
Also follow the simple sample code- https://github.com/mongodb/node-mongodb-native#introduction, substitute the database name and a collection name and run that on node
node sample.js

Related

Unable to create MongoDB database using Node.js

I am trying to run the below program to create a mongo database using Node.js by running node app.js.
app.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://hostname:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Below is the error I'm getting :-
(node:20815) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [hostname_fqdn:27017] on first connect [Error: connect ECONNREFUSED 10.127.45.59:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:223:5)
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:995:11
at /root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:32:7
at callback (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at Socket.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:310:7)
at Object.onceWrapper (events.js:313:26)
at Socket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8) {
name: 'MongoNetworkError'
}
The file/node_modules/package.json all are located in a CentOS Virtual Machine.
You need to start the MongoDB Service after installing.
Edited:
If you have already started service and connecting mongo via terminal, then try to remove mongo lock file (rm /var/lib/mongodb/mongod.lock) and repair mongod (mongod -–repair). Now start mongo service and see if you can connect. I had similar issue with EC2 and Compass and tried above to resolve.

Error: spawn node ENOENT

I'm working on my Electron app with Express server and when I build it with electron-packager, I get an error.
Uncaught Exception:
Error: spawn node ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:607:11)
at startup (bootstrap_node.js:167:16)
at bootstrap_node.js:589:3
here is my main.js where child process is called
const cp = require('child_process');
let instance = cp.spawn('node',['./app.js']);
var electron = require('electron');
var browserWindow = electron.BrowserWindow;
var app = electron.app;
app.on('ready', function(){
// appWindow
var appWindow;
appWindow = new browserWindow({
width:1120,
height:620,
webPreferences: {
plugins: true
},
icon: __dirname + '/public/icon/icon.png'
});
appWindow.loadURL('file://' +__dirname + '/public/prva.html');
//appWindow.webContents.openDevTools();
});
// close app after all windows are closed
app.on('window-all-closed', () => {
app.quit()
})
Does anyone know solution for this error?
You most likely have a problem with your app.js script. You should hook onto some of the event listeners to understand what's really going on. There's an error, exit, close, disconnect, and message events you can listen for. You can also hook onto a number of other things such as the stdin, stdout, stderr as well. Checkout the documentation for the different events, hook onto all of them and output some information and you should be able to track down the issue.
You should also check to see if your express services runs properly directly from the command line rather than from within this Electron app. If it does then you've likely got a path wrong. This could be either that child_process cannot find the "node" application to run, or it can't find your startup script. In either case, you can use the path module to build up the correct path.

error: password authentication failed for user "myuser"

If I have a record in /etc/postgresql/9.4/main/pg_hba.conf which specifically trusts my specific user
# TYPE DATABASE USER ADDRESS METHOD
local all myuser trust
Since I'm on debian I restart postgresql like this
sudo /etc/init.d/postgresql restart
Here is my entire source file testing this out:
const pg = require('pg');
const connectionString = "postgres://myuser:mypassword#localhost/mydbname";
const client = new pg.Client(connectionString);
client.connect();
const query = client.query('SELECT * FROM USERS');
query.on('end', () => { client.end(); });
and this is the error I consistently get:
error: password authentication failed for user "myuser"
at Connection.parseE (/home/myuser/webserver/node_modules/pg/lib/connection.js:539:11)
at Connection.parseMessage (/home/myuser/webserver/node_modules/pg/lib/connection.js:366:17)
at Socket.<anonymous> (/home/myuser/webserver/node_modules/pg/lib/connection.js:105:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:551:20)
It's also worth noting that doing the following works:
psql -h localhost -U myuser mydb
What am I doing wrong here?
As the documentation states, local is only for UNIX socket connections, while you are establishing a TCP connection to localhost.
Use a line like this:
host all myuser 127.0.0.1/32 trust
to trust all connections from localhost using IPv4 (use the adress ::1/128 for IPv6).

node-transmission package not working

I tried installing this package : https://github.com/FLYBYME/node-transmission in my local nodejs installation but I am getting following error while running example.js from the above github repository.
Error: connect ECONNREFUSED 127.0.0.1:9091
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 9091
After a bit research I tried to run a server at port 9091 using this code(in a separate server.js file)
const http = require('http')
const port = 9091
const requestHandler = (request, response) => {
console.log(request.url)
response.end('Hello Node.js Server!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
After running a server on port 9091, I started getting this error with example.js :
SyntaxError: Unexpected token H in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.onEnd (F:NodeJS\node-transmission-master\lib\transmission.js:453:33)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
What must be causing this? I have no idea which step I have done wrong. That's why I described the whole process I followed.
I am very new to nodejs. Any help will be deeply appreciated.
The library is expecting a JSON formatted response and you are sending a simple text response. If you look through their source code you can see that their callServer function expects a stringified JSON but I can't see that in their docs.
You can change your code like so:
const http = require('http')
const port = 9091
const requestHandler = (request, response) => {
console.log(request.url)
// Format your response as a stringified JSON
response.end(JSON.stringify({message: 'Hello Node.js Server!'}));
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
In order to run the example from the node-transmission package, you need first to install and start the transmission-daemon.
The following steps are for Ubuntu:
Login as root or change to root with su - (be always careful what you do/install as root)
Install the transmission-daemon linux package: apt-get install transmission-daemon
Edit the daemon configuration for either disabling authentication or setting up your username/password (there is no default password). You can disable authentication by editing the relative flag in the configuration file:
pico /etc/transmission-daemon/settings.json
Set the auth flag to false: rpc-authentication-required:false
Press Ctrl-X then Y and then Enter to save the change
Start the daemon: start transmission-daemon
You should be able now to execute successfully the example.js and download its torrent link.

Node.js/MongoDB: How can I use module.exports to pass a localhost database url to server.js file?

I have a problem with connection to a database with mongoose on localhost.
In my server.js file I have:
var express = require('express');
var app = express(); //Create our app with express
var mongoose = require('mongoose'); //Mongoose for mongoDB
var database = require('./config/database.js'); //Load the database config
...
//Configuration =====================
mongoose.connect('database.url'); //Connect to mongoDB database
...
In my database.js file I have:
// Config/database.js
module.exports = {
url : 'mongodb://127.0.0.1:27017/test'
};
The error I get in my node.js command prompt is:
events.js:141
throw er; // Unhandled 'error' event
^
Error: failed to connect to [database.url:27017]
at null.<anonymous> (C:\*filepath*\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:540:25)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (C:\*filepath*\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:140:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (C:\*filepath*\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection.js:478:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1256:8)
When I use mongodb://127.0.0.1:27017/test in place of database.url it works just fine.
I'm currently using node.js v4.2.6 and mongodb 3.2 on Windows 10.
How can I get module.exports to pass the url to the server.js?
Remove '', because now you are trying connect to mongodb with url 'database.url', but you need use url property from database that contains right url mongodb://127.0.0.1:27017/test
mongoose.connect(database.url);
Have you tried taking it out of speech marks?
mongoose.connect('database.url');
is trying to connect to the address 'database.url'
mongoose.connect(database.url);
will get the url property of database

Categories