-2

So I followed a tutorial on youtube and created a project using node js, express in VS Code and a local mongodb. Went fine. Next step: Use a db in Mlab(Cloud mongodb) instead of your local db. Done and done, I can see products from my seeder in Mlab. Thing is, now I would like to actually go in to the site (which was a localhost:5000) and add some users etc, to see what happens. So I go about it like I usually do "npm start" "localhost" in chrome, and it gives me the localhost I have been using, but it just keeps loading before finally timing out. How do I visit my site?

I get this error from my browser "ERR_CONNECTION_REFUSED" OR "ERR_EMPTY_RESPONSE" when I connect to localhost. No console errors.

Here is my github repo if you want to see everything (username/pass is not active anymore): https://github.com/KarbelIlias/Node.js-Express-MongoD-app

this is my app.js connecting to mlab db

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var validator = require('express-validator');
var MongoStore = require('connect-mongo')(session);

var url = 'mongodb://Chabbe:XXXX@ds143754.mlab.com:43754/gamestore';

var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } }, 
                replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
// mongoose.connect(url,options);
mongoose.createConnection(url, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:')); 
conn.once('open', function() {
  // Wait for the database connection to establish, then start the app.                         
console.log('db connection established');
});

var index = require('./routes/index');
var userRoutes = require('./routes/user');

var app = express();  

require('./config/passport');
require('./models/product-seeder');

// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());

app.use(session({
  secret: 'myCurrentSession', 
  resave: false, 
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: conn }),
  cookie: { maxAge: 10 * 60 * 1000 }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
  res.locals.login = req.isAuthenticated();
  res.locals.session = req.session;
  next();
});

app.use('/user', userRoutes);
app.use('/', index);
console.log("use-routers");
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);  
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');  
});

module.exports = app;
console.log("app-export");

this is my product seeder (These products show upp on Mlab website)

var mongoose = require('mongoose');
var Product = mongoose.model('Product');

var url = 'mongodb://Chabbe:XXXX@ds143754.mlab.com:43754/gamestore';
console.log("under url-seeder");
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } }, 
                replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
mongoose.createConnection(url, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
console.log("inside product seeder");
conn.once('open', function() {
    var products = [
        new Product({
        imagePath: 'https://paarpsskoltidning.files.wordpress.com/2015/10/csgo4.jpg',
        title: 'CS:GO',
        description: 'Awesome fucking game!',
        price: 15
        }),
        new Product({
        imagePath: 'https://dvsgaming.org/wp-content/uploads/2015/06/World-Of-Warcraft-Logo2.jpg',
        title: 'World of Warcraft',
        description: 'Insane game!!',
        price: 20
        }),
        new Product({
        imagePath: 'http://mp1st.com/wp-content/uploads/2017/04/Call-of-Duty-WWII.jpg',
        title: 'Call of Duty',
        description: 'Crazy FPS!',
        price: 10
        }),
        new Product({
        imagePath: 'https://vice-images.vice.com/images/content-images-crops/2016/05/11/discussing-the-importance-of-doom-with-game-designer-dan-pinchbeck-doom-week-body-image-1462983105-size_1000.jpg?output-quality=75',
        title: 'DOOM',
        description: 'Classic cult fps-game!',
        price: 8
        }),
        new Product({
        imagePath: 'https://farm6.staticflickr.com/5624/23815901722_4d1edf4ed1_b.jpg',
        title: 'Uncharted 4',
        description: 'Adventoures third-person game!',
        price: 27
        }),
        new Product({
        imagePath: 'https://compass-ssl.xbox.com/assets/aa/07/aa07eaf5-f2e6-46a4-be25-5ec427842ed1.jpg?n=Xbox-One-S-GOW-4_Blade_1600x700.jpg',
        title: 'Gears of War 5',
        description: 'Crazy third-person shooter!',
        price: 20
        })
    ];

    Product.insertMany(products, function (err, docs) {
      if (err) throw err;
      mongoose.connection.db.close(function(err) {
        if (err) throw err;
      });
    });

});

this is one of my models:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var schema = new Schema({
    imagePath: {type: String, required: true},
    title: {type: String, required: true},
    description: {type: String, required: true},
    price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', schema);
console.log("done product schema");

Edit: added var schema = new Schema({..}, { bufferCommands: false }); as anon requested and got this error message:

events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'length' of undefined
    at C:\Users\Charbel Ilias\Shop\routes\index.js:17:32
    at C:\Users\Charbel Ilias\Shop\node_modules\mongoose\lib\model.js:3835:16
    at C:\Users\Charbel Ilias\Shop\node_modules\kareem\index.js:213:48
    at C:\Users\Charbel Ilias\Shop\node_modules\kareem\index.js:131:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

this is part of my index.js:

//GET EXPRESS ROUTING
var express = require('express');
var router = express.Router();

//GET MODELS
var Cart = require('../models/cart');
var Product = require('../models/product');
var Order = require('../models/order');

/* GET home page. */
router.get('/', function(req, res, next) {
  var successMsg = req.flash('success')[0];
    // console.log(req);
    // console.log(res);
    // console.log(next);
    console.log(next);

  Product.find(function(err, docs) {
    console.log(docs);
        var productChunks = [];
        var chunkSize = 3;
        for(var i = 0; i < docs.length; i += chunkSize) {
          productChunks.push(docs.slice(i, i + chunkSize));
        }
        res.render('shop/index', { title: 'ShopCart', products: productChunks, successMsg: successMsg, noMessages: !successMsg });
  });
});


// GET Add to cart
router.get('/add-to-cart/:id', function(req,res,next) {
    var productId = req.params.id;
    var cart = new Cart(req.session.cart ? req.session.cart : {});

    Product.findById(productId, function(err, product) {
        if (err) {
          return res.redirect('/');
        }
        cart.add(product, product.id);
        req.session.cart = cart;
        console.log(req.session.cart);
        res.redirect('/');
    });
});

// GET Reduce shopping cart items
router.get('/reduce/:id', function(req, res, next) {
  var productId = req.params.id;
  var cart = new Cart(req.session.cart ? req.session.cart : {});

  cart.reduceByOne(productId);
  req.session.cart = cart;
  res.redirect('/shopping-cart');
});

// GET Remove shopping cart items
router.get('/remove/:id', function(req, res, next) {
  var productId = req.params.id;
  var cart = new Cart(req.session.cart ? req.session.cart : {});

  cart.removeItem(productId);
  req.session.cart = cart;
  res.redirect('/shopping-cart');
});

// GET Shopping cart
router.get('/shopping-cart', function(req, res, next) {

    if (!req.session.cart) {
      return res.render('shop/shopping-cart', {products: null});
    }
    var cart = new Cart(req.session.cart);
    res.render('shop/shopping-cart', {products: cart.generateArray(), totalPrice: cart.totalPrice});
});

1 Answers1

0

If you are running it on port 5000 you must specify that in chrome. On that note, I don't actually see where you are setting the port. Is it located in a different js file?

edit: I found this, "If you have bufferCommands on and your connection is hanging, try turning bufferCommands off to see if you haven't opened a connection properly."

bufferCommands is on by default. If you turn it off you should get an error on what it is hung on.

You turn bufferCommands off on you schema like,

var schema = new Schema({..}, { bufferCommands: false });

edit: double check that you have created the user and the user has permissions to the database on the mlab side. Here is the documentation on how to create admin and how to use it.

anon
  • 11
  • 2
  • yes, I specify that "localhost:5000" everything worked when I had a local db, I could se all products, make "purchases" and so on. The port i set in /bin/www " var port = normalizePort(process.env.PORT || '5000'); app.set('port', port);" – swedish_junior_dev Sep 25 '17 at 14:09
  • Alright, I added the buffecommand to all my models and ran the application. I got an error message. Will edit in bottom of my post! – swedish_junior_dev Sep 25 '17 at 14:59
  • Okej, ill post it now. – swedish_junior_dev Sep 25 '17 at 15:36
  • I followed a tutorial, so Im not sure, but I think its supposed to be the objects (products) that you get back from the database. Im using a seeder and populating it, and in my "/" I loop through the products that I get from that function. It worked fine when I had a local mongodb. – swedish_junior_dev Sep 25 '17 at 17:03
  • yes, but when I change it on app.js and product-seeder I get an error saying: "connection error: { Error: Trying to open unclosed connection." I saw other people having this problem and they solved it like this. I got it from here: https://stackoverflow.com/questions/25250544/why-am-i-getting-error-trying-to-open-unclosed-connection – swedish_junior_dev Sep 25 '17 at 17:31
  • I have a user, but not an admin since its "Available for Dedicated plans only". But I have populated the products table with my products from the seeder-class so it works in that case anyways. – swedish_junior_dev Sep 27 '17 at 09:29