尝试使用Mlab mongodb启动我的节点js应用程序

时间:2017-09-25 13:14:55

标签: node.js mongodb express npm visual-studio-code

所以我在youtube上关注了一个教程,并使用节点js创建了一个项目,在VS Code中表达了一个本地mongodb。好的。下一步:在Mlab(Cloud mongodb)中使用db而不是本地db。做完了,我可以在Mlab看到我的播种机中的产品。 事情是,现在我想实际进入该网站(这是一个localhost:5000)并添加一些用户等,看看会发生什么。所以我像往常一样去做#34; npm start" "本地主机"在chrome中,它给了我一直在使用的本地主机,但它只是在最终超时前继续加载。我如何访问我的网站?

我从浏览器中收到此错误" ERR_CONNECTION_REFUSED"或" ERR_EMPTY_RESPONSE"当我连接到localhost时。没有控制台错误。

如果你想查看所有内容(用户名/通行证不再有效),这是我的github回购:https://github.com/KarbelIlias/Node.js-Express-MongoD-app

这是我的app.js连接到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");

这是我的产品播种机(这些产品在Mlab网站上显示upp)

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;
      });
    });

});

这是我的模特之一:

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");

修改:已添加var schema = new Schema({..}, { bufferCommands: false }); 正如anon所要求并收到此错误消息:

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)

这是我的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 个答案:

答案 0 :(得分:0)

如果您在端口5000上运行它,则必须在chrome中指定它。在那个问题上,我实际上并没有看到你在哪里设置端口。它位于不同的js文件中吗?

编辑: 我发现这个,“如果你打开了bufferCommands并且你的连接挂了,请尝试关闭bufferCommands以查看你是否没有正确打开连接。”

默认情况下,

bufferCommands处于启用状态。如果你关闭它,你应该得到一个错误。

您可以在模式上关闭bufferCommands,例如

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

编辑:仔细检查您是否已创建用户,并且用户对mlab端的数据库具有权限。 Here是有关如何创建管理员以及如何使用管理员的文档。