我在node.js应用程序中,我正在尝试将会话数据存储在mongoDB数据库中。
但我不明白connect-mongo的用法,我想如果有人能向我解释正确的用法以及我无法连接到我的mongoDB数据库。
我的app.js代码是
var config = require('./config')
, express = require('express')
, passport = require('passport')
, site = require('./site')
, oauth2 = require('./oauth2')
, user = require('./user')
, client = require('./client')
, token = require('./token')
, https = require('https')
, fs = require('fs')
, path = require('path')
, mongoose = require('mongoose')
, MongoStore = require('connect-mongo')(express);
var sessionStorage;
var MongoStore = require('connect-mongo')(express);
console.log('Using MongoDB for the Session');
sessionStorage = new MongoStore({
db: config.session.dbName
});
var app = express();
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.urlencoded());
app.use(express.json());
//Session Configuration
app.use(express.session({
secret: config.session.secret,
store: sessionStorage,
key: "authorization.sid",
cookie: {maxAge: config.session.maxAge }
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(function(err, req, res, next) {
if(err) {
res.status(err.status);
res.json(err);
} else {
next();
}
});
require('./auth')(passport);
app.get('/', site.index);
app.get('/login', site.loginForm);
app.post('/login', site.login);
app.get('/logout', site.logout);
app.get('/account', site.account);
app.get('/dialog/authorize', oauth2.authorization);
app.post('/dialog/authorize/decision', oauth2.decision);
app.post('/oauth/token', oauth2.token);
app.get('/api/userinfo', user.info);
app.get('/api/clientinfo', client.info);
app.get('/api/tokeninfo', token.info);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://user:pass@host:10026/dbName');
var db = mongoose.connection;
db.on('error',console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
console.log("Connected to db");
});
mongoose.set('debug', true);
var options = {
key: fs.readFileSync('certs/privatekey.pem'),
cert: fs.readFileSync('certs/certificate.pem')
};
https.createServer(options, app).listen(3000);
console.log("Authorization Server started on port 3000");
,输出错误是
authorization-server\node_modules\connect-mongo\lib\connect-mongo.js:155
throw new Error('Error connecting to database <' + err + '>');
^
Error: Error connecting to database <Error: failed to connect to [127.0.0.1:27017]>
答案 0 :(得分:0)
请注意,在您的错误消息中,mongoose正在尝试连接到默认端口的localhost。您还需要在文件顶部定义数据库连接。
更改:
mongoose.connect('mongodb://user:pass@host:10026/dbName');
致:
mongoose.connect('mongodb://localhost/dbName');