web page does not receive data from mongodb - mongodb

I am a beginner.
I installed Bitnami MEAN stack and I have a question.
"[]" shows on the web page when I enter http://127.0.0.1:3000/tableList.
I want to know why the web page does not show the data in collections.
On Command Prompt:
C:\Bitnami\meanstack-3.2.3-1\test>SET DEBUG=test:* & npm start
test#0.0.0 start C:\Bitnami\meanstack-3.2.3-1\test
node ./bin/www
test:server Listening on port 3000 +0ms
connection successful
[]
GET /tableList 304 30.004 ms - -
GET /favicon.ico 200 7.164 ms - 1183
On mongodb.log file:
2016-04-05T00:08:04.350+0700 I NETWORK [initandlisten] connection accepted from 127.0.0.1:52192 #6 (4 connections now open)
2016-04-05T00:08:04.513+0700 I ACCESS [conn6] Successfully authenticated as principal chai on khamoo
On app.js file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://chai:chai#localhost/khamoo', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
mongoose.model('tableList',{tid: String});
app.get('/tableList', function(req, res) {
mongoose.model('tableList').find(function(err,tableList){
console.log(tableList);
res.json(tableList);
});
});

Related

Express session, passport and connect-pg-simple issue in production

This is my first time posting a question up here. I hope you guys can help me out with this. I am fairly new to node.js, express, so sorry in advance for my inexperience.
I am currently having a problem with my authentication session in my node.js, express app. I use Passport.js to handle my authentication, I store the login session with connect-pg-simple (a PostgreSQL session store). After clicking the login button, the session was stored inside my PostgreSQL database, but somehow express couldn't find it. In fact, it stores the session twice in the database, but only one of them got the passport cookie in it.
This issue was not present when the server was still on localhost. It appears when I host my server on Heroku.
Also, whenever I push to heroku repo, it shows this warning:
"connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process."
My guess is I didn't connect express session to the PostgreSQL express store properly. Below is my code:
This is how I set up the PostgreSQL database:
const Pool = require("pg").Pool;
const pool = new Pool({
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: process.env.PGHOST,
port: process.env.PGPORT,
database: process.env.PGDATABASE
});
module.exports = pool
This is how I set up the session:
const poolSession = new (require('connect-pg-simple')(session))({
pool : pool
})
app.set('trust proxy', 1);
app.use(session({
store: poolSession,
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: false,
cookie: {
secure: true,
maxAge: 30 * 24 * 60 * 60 * 1000
} // 30 days
}));
app.use(passport.initialize());
app.use(passport.session());
This is the image of 2 sessions were store in the database when clicking the login button
https://i.stack.imgur.com/lzAby.png
This is my login route (when click the login button):
router
.route("/signin")
.post((req, res, next) => {
console.log("Signing in...")
passport.authenticate('local', function(err, user, info) {
//code....
req.logIn(user, function(err) {[enter image description here][1]
console.log(user);
if (err) {
console.log(err);
res.send(apiResponse(500, err.message, false, null))
return next(err);
}
console.log(req.sessionID); //The id of the 1st session store in db
console.log(req.isAuthenticated()) //True
res.redirect('/auth');
});
})(req, res, next);
})
This is the route that is redirected to when login successfully:
router.get("/", (req, res) => {
console.log("/ ", req.isAuthenticated()); //False
console.log("/ ", req.sessionID); //The Id of the 2nd session store in db
if(req.isAuthenticated()){
//Notify user login success
}
});
I have been stuck here for a few days now. Please tell me if you need more code!

How to fix "[nodemon] app crashed - waiting for file changes before starting" in connecting mongodb

I can't connect to the mongoDB, this is the error I'm getting each time:
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server started on port 5000
Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Already tried:
- changing ip access on mongoDB from everywhere to current ip adress and otherwise,
- creating new account that was for sure made on my current ip adress,
- disabling firewall,
- checked code for errors,
- tried restarting my pc for some reason
here is my code
//////server.js/////
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect Database
connectDB();
app.get('/', (req, res) =>
res.json({ mgs: 'Welcome to the ContactKeeper API...' })
);
// Define Routes
app.use('/api/users', require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/contacts', require('./routes/contacts'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
//////default.json/////
{
"mongoURI": "mongodb+srv://artur123:<artur123>#contactkeeper-lv2py.mongodb.net/test?retryWrites=true&w=majority"
}
//////db.js/////
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = () => {
mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB Connected'))
.catch(err => {
console.error(err.message);
process.exit(1);
});
};
module.exports = connectDB;
You just have to add your ip in the ip whitelist on mongoDB Atlas under :
Network Access
then restart.

Heroku - Unable to deploy MongoDB Node Application

I have a Node MongoDB application that I am trying to deploy to heroku. I have added mongolab to my application, but I continue to get an "application error."
This is my app on GitHub: GitHub
Here is my app.js:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var app = express();
var port = process.env.PORT || 3000;
mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/foobar');
// mongodb connection
mongoose.connect("mongodb://localhost:27017/pingpong");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
// use sessions for tracking logins
app.use(session({
secret: 'treehouse loves you',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
// make user ID available in templates
app.use(function (req, res, next) {
res.locals.currentUser = req.session.userId;
next();
});
// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// serve static files from /public
app.use(express.static(__dirname + '/public'));
// view engine setup
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
// include routes
var routes = require('./routes/index');
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// listen on port 3000
app.listen(3000, function () {
console.log('Express app listening on port 3000');
});
In addition, here are my heroku logs:
2017-09-24T18:50:56.086372+00:00 app[web.1]: message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]' }
2017-09-24T18:50:56.086371+00:00 app[web.1]: name: 'MongoError',
This is the heroku link I am trying to deploy to: Heroku App
I have followed the following steps:
heroku login
heroku apps:create missy-pong
heroku addons:create mongolab
heroku git:remote -a missy-pong
git push heroku master
heroku open
If anyone has any idea how to resolve this issue I would really appreciate it!
Run heroku config and check if MONGOLAB_URI is the variable being configured.
I had a similar issue, and when I checked heroku config I found out that the mongodb uri that was being set by heroku was MONGODB_URI and NOT MONGOLAB_URI

Auth0 Custom database mongodb

I'm trying to store users on my own mongo database not the default (auth0 server).
Below is the script:
function create (user, callback) {
mongo('mongodb://admin:pass#localhost:27017/mydb', function (db) {
var users = db.collection('subscribers');
users.findOne({ email: user.email },
function (err, withSameMail) {
if (err) return callback(err);
if (withSameMail) return callback(new Error('the user already exists'));
user.password = bcrypt.hashSync(user.password, 10);
users.insert(user, function (err, inserted) {
if (err) return callback(err);
callback(null);
});
});
});
}
This is the error I'm getting when I try to create a user:
[Error] Error: socket hang up
at createHangUpError (_http_client.js:200:15)
at Socket.socketOnEnd (_http_client.js:285:23)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)
Your mongodb is in localhost (see your connection string). The create script runs in Auth0 servers, so localhost (your machine) is not reachable.
Normally your instance would run on a server that is reachable from Auth0 (e.g. mongolabs, a server in AWS, etc). If you are testing, then you might want to check out ngrok
Blakes suggestion of caching the connection is a good one, but it is an optimization, not the reason it is not working.

MongoJS, Node, MongoLab - How to get the database online

I have created an hybrid application with Ionic, MongoJS, Angular JS (Mean Stack).
My application worked fine, locally. This means my mongod (Mongo Service) and my mongo ran locally on my pc. I also have a server.js (node) which is located locally.
Now I would like to use MongoLab (MongoDB as a Service) to change the location of my database from local to online.
I intented to change just the connection path, but for some reason I receive an undefined through my http get request.
My code:
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
//var db = mongojs('nzbaienfurtdb', ['nzbaienfurtdb']); // This is my old mongojs which ran locally and worked fine.
var databaseUrl = 'mongodb://dbuser:password#ds045604.mongolab.com:45604/nzbaienfurtdb';
var db = mongojs(databaseUrl, ['nzbaienfurtdb']); // database online with MongoLab
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/www"));
app.use(bodyParser.json());
app.get('/nzbaienfurtdb', function (req, res) {
console.log("I received a GET request")
db.nzbaienfurtdb.find(function (err, docs){
console.log(docs);
res.json(docs);
});
});
app.listen(3000);
console.log("server running on 3000");
This is a part of my get request out of a service:
service.js
return {
getUsers: function(){""
$http.get("/nzbaienfurtdb")
.success(function(data, status, headers, config){
headers("Cache-Control", "no-cache, no-store, must-revalidate");
headers("Pragma", "no-cache");
headers("Expires", 0);
users = angular.fromJson(data);
})
.error(function(data, status, headers, config){
console.log('Data could not be loaded, try again later');
})
return users;
}
MongoLab has been setup already.
My questions:
Why do I get an undefined for my http GET Request?
What happens with my server.js file when I want to deploy the Ionic App on for example an Android Phone? Is the server running on the device?
Since I have changed the var db variable i get also the following error message in my chrome console:
--------- ERROR CODE:
SyntaxError: Unexpected end of input
at Object.parse (native)
at Object.fromJson (http://localhost:3000/lib/ionic/js/ionic.bundle.js:8764:14)
at http://localhost:3000/js/userServices.js:23:27
at http://localhost:3000/lib/ionic/js/ionic.bundle.js:15737:11
at wrappedCallback (http://localhost:3000/lib/ionic/js/ionic.bundle.js:19197:81)
at wrappedCallback (http://localhost:3000/lib/ionic/js/ionic.bundle.js:19197:81)
at http://localhost:3000/lib/ionic/js/ionic.bundle.js:19283:26
at Scope.$eval (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20326:28)
at Scope.$digest (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20138:31)
at Scope.$apply (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20430:24)
I hope somebody can help me out, I am fighting now for ages!
Thank you in advance, guys!
This issue has been resolved after ages!
I had to enable the API on the website of mongolab in my configuration.