NodeJS: MongoDB not connecting in Node app - node.js

My app in nodeJS refuses to connect to the database when I run it, I am using mongoose ODM to connect to the database. When I run the application I get the error below.
Server running at port 8000
/Users/user/www/document-manager/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
Error: connect ECONNREFUSED 127.0.0.1:27017
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1065:14)
Below is the code which I run:
var express = require('express'),
mongoose = require('mongoose'),
dotenv = require('dotenv'),
bodyParser = require('body-parser'),
router = require("./server/router");
//Initialize App
var app = express();
app.use(bodyParser.json());
//Initialize database connection
mongoose.connect("mongodb://localhost/dms");
router(app);
//Load Dotenv
dotenv.load();
//Set Port
var port = process.env.PORT || 8080;
//Run applicatino
app.listen(port, function(){
console.log("Server running at port " + port);
});
The application would run if I run mongod from the terminal separately. Is there a way to run my database server and my application server together?

Related

Trying to connect Express server to make POST/GET requests to PostgreSQL database

I have looked around for a solution, but I can't seem to figure this out. What I'm trying to do is make POST/GET requests to a PostgreSQL database from an Express server.
main.js:
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port, () => {
console.log(`Server is running on localhost:${port}`);
});
server.on('error', onError);
server.on('listening', onListening);
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');
var indexRouter = require('./routes');
var app = express();
app.use(cors());
app.use(helmet());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
module.exports = app;
routes.js (Handling the api requests)
router.post('/api/post/userprofiletodb', async (req, res, next) => {
console.log(req);
const values = [req.body.profile.nickname, req.body.profile.email, req.body.profile.email_verified];
// ON CONFLICT DO NOTHING - prevents the user profile from being stored in db twice
await pool.query(`INSERT INTO users(username, email, email_verified, date_created)
VALUES($1, $2, $3, NOW() )
ON CONFLICT DO NOTHING`, values,
(q_err, q_res) => {
if (q_err) return next(q_err);
console.log(q_res);
res.json(q_res.rows);
})
})
router.get('/api/get/userprofilefromdb', async (req, res, next) => {
console.log(req);
const email = String(req.query.email);
await pool.query(`SELECT * FROM users WHERE email=$1`, [email],
(q_err, q_res) => {
if (q_err) return next(q_err);
res.json(q_res.rows);
})
})
db.js:
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'mydb',
password: 'mypassword',
post: 5432
});
module.exports = pool;
React code (Action Creators for Redux):
export const setDbProfile = (profile) => async(dispatch) => {
const response = await axios.post('http://localhost:8000/api/post/userprofiletodb', profile);
dispatch({ type: SET_DB_PROFILE, payload: response.data });
console.log(response);
history.replace('/');
}
export const getDbProfile = (profile) => async(dispatch) => {
const data = profile;
console.log('getDbProfile', profile);
const response = await axios.get('http://localhost:8000/api/get/userprofilefromdb',
{
params: {
email: data.profile.email
}
}
)
dispatch({ type: GET_DB_PROFILE, payload: response.data });
history.replace('/');
Here is my thought process:
- I have my Express server set up on http://localhost:8000 and my React application is running on http://localhost:3000 (I have already included a proxy in the package.json file).
- When the action creator is called, it first does a post request to http://localhost:8000 where my Express server is on.
- The Express server sees this and makes a request to the PostgreSQL database stored on localhost: 5432.
However, I'm getting this error....
POST /api/post/userprofiletodb 500 182.558 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
GET /api/get/userprofilefromdb?email=dasfdfasfdf#gmail.com 500 52.541 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
I think there may be an issue with my PostgreSQL database. How I set that up is by opening up SQL Shell (psql) and did the following:
- CREATE DATABASE mydb;
- \c mydb
- CREATE TABLE users(...);
- CREATE TABLE posts(...);
- CREATE TABLE comments(...);
Not too sure how I could solve this... Any guidance would be greatly appreciated! Cheers.
UPDATE:
When I run the command
netstat -na
I do not see, 127.0.0.1.5432 listed at all... Does this mean my database is just not setup properly?
Running SQL Shell (psql)
x-MacBook-Air:~ x$ /Library/PostgreSQL/12/scripts/runpsql.sh; exit
Server [localhost]:
Database [postgres]:
Port [5000]: 5432
Username [postgres]:
psql: error: could not connect to server: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Press <return> to continue...

trying to connect to mongodb Atlas using nodeJs

I am working on a small project(REST API) using nodeJs + MongoDB. I have been able to install MongoDB locally and connect to it using mongoose. However for some reason, when I try to connect using MongoDB Atlas it fails. It looks like it connects but then after 2 seconds, I get an error message saying sockets closed(see error below). I have no clue what is going on. I have whitelisted my IP, checked my login info to make sure I am using the correct password and indeed I am using because I am able to connect using MongoDB compass. Any help is greatly appreciated.
My current local ENV package versions are:
nodeJs:V9.7.1
mongoose:V6.1
=== MongoDb Atlas ===
mongodb:3.6
Below is the code that I am using to connect to the database:
var express = require('express'),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
user = require('./api/models/userModel'),
config = require('./api/config');
bodyParser = require('body-parser');
var authRoutes = require('./api/routes/authRoutes'),
userRoutes = require('./api/routes/userRoutes'),
reviewRoutes = require('./api/routes/reviewRoutes');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://user:myPass#cluster0-shard-00-00 zd6jq.mongodb.net/myDb');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Swagger Info
var options = {
explorer : true
};
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
//END Swagger Info
//REGISTER ROUTES
userRoutes(app);
authRoutes(app);
reviewRoutes(app);
app.listen(port);
console.log('iReview RESTful API server listenning on port: ' + port);
module.exports = app;
====ERROR MESSAGE ===
/Users/mdiez/node_test/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
MongoError: server cluster0-shard-00-00-zd6jq.mongodb.net:27017 sockets closed
at Pool.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/topologies/server.js:325:47)
at Object.onceWrapper (events.js:219:13)
at Pool.emit (events.js:127:13)
at Connection.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/pool.js:101:12)
at Object.onceWrapper (events.js:219:13)
at Connection.emit (events.js:127:13)
at Socket.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/connection.js:142:12)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at TCP._handle.close [as _onclose] (net.js:558:12)
var uri = 'mongodb://<usernamr>:<password>#<clustername>/<dbname>?ssl=true&replicaSet=<replica setname>&authSource=admin';
var db = mongoose.connect(uri).catch((error) => { console.log(error); });
Specify the replica set name, ssl true and authentication database. This is based on reference from Atlas documentation.
You can use this code to connect to Compass and Application. You just need to the following:
replace all the three primary and secondary shard from Cluster -> Overview
replace natours-app with your cluster name.
Compass:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?authSource=admin&replicaSet=natours-app1-shard-0&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true
Application:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?ssl=true&replicaSet=natours-app-shard-0&authSource=admin&retryWrites=true

EC2 Instance is only listening to Port 22

I am trying to deploy a node app into AWS EC2 Ubuntu instance, but I am getting issues. It seems like for some reason it is only listening to port 22 (the default portal for SSH), and not my HTTP port.
netstat -ntlp | grep LISTEN
AWS Security Group Settings
As you can see in the link above, I did manually include port 80 as well as others into my security group. I don't think this is a firewall issue from what I have read.
My Express server code:
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieSession = require('cookie-session'),
port = 8000,
mongoose = require('mongoose'),
mongoDB = require('./keys.js').database,
passport = require('passport'),
passportSetup = require('./passportConfig'),
keys = require('./keys'),
bluebird = require('bluebird');
mongoose.Promise = bluebird;
app.listen(port, () => {
mongoose.connect(mongoDB)
.then(() => {
console.log('successfully connected to MongoDB. Listening to
port ', port);
})
.catch(() => {
console.log('error connecting to MongoDB.');
});
});
I am able to actually access my Node server, but connection is refused in the browser.
NPM Start
Anyone have any ideas?

Nodejs app is stuck at express:dev task?

screenshot of terminal
When running grunt serve the process gets stuck at express:dev task
while mongod is running and showing
> Running "express:dev" (express) task
> Starting background Express server
> Debugger listening on port 5859
Mongod response:
2016-12-24T19:50:20.085+0530 I NETWORK [initandlisten] waiting for connections on port 27017
2016-12-24T19:50:36.539+0530 I NETWORK [initandlisten] connection accepted from 127.0.0.1:36894 #1 (1 connection now open)
2016-12-24T19:50:36.572+0530 I NETWORK [initandlisten] connection accepted from 127.0.0.1:36896 #2 (2 connections now open)
My server app.js file is hereby and i don't know why grunt further task are executing is it something related to port please help ?
[/**
* Main application file
*/
'use strict';
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
// Populate DB with sample data
// if(config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io')(server, {
serveClient: (config.env === 'production') ? false : true,
path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// Start server
server.listen(config.port, config.ip, function () {
//console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
// Expose app
exports = module.exports = app;][1]

Node.js with Express fails to connect to MongoDb - Error: connect ECONNREFUSED

If I don't start a connection to mongo on port 27017 via mongod in my console, when I try starting my Express server I get the following error:
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1000:19)
If do I connect via mongod in another shell, and then run node app.js, it works just fine.
//app.js
var express = require('express'),
app = express(),
MongoClient = require('mongodb').MongoClient;
app.route('/')
.get(function(req, res){
res.send("Hello, World!")
global.db.close();
});
MongoClient.connect('mongodb://localhost:27017/nvps', function (err , database) {
if(err) throw err;
global.db = database;
app.listen(3000, function(){
console.log('Express server started on port 3000');
});
});
Why doesn't the mongo connection get initiated when I go to http://localhost:3000/ on my machine?

Resources