我在运行我的meanjs项目时得到了Unhandled rejection MongoError: cannot connect to server
。
以前运行正常,但在更新nodejs 5.11.1
,mongodb 3.2.6
,"mongoose": "^4.4.16"
和"connect-mongo": "^1.1.0",
时会出现此错误。
配置文件代码中的未处理拒绝MongoError:无法连接到服务器 在Collection.listIndexes(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1750:11) 在indexInformation(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1625:25) 在Db.indexInformation(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1589:44) 在ensureIndex(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1082:8) 在Db.ensureIndex(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/db.js:1058:44) 在ensureIndex(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1820:13) 在Collection.ensureIndex(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/mongodb/lib/collection.js:1808:44) 在MongoStore.setAutoRemoveAsync(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:123:40) 在MongoStore.handleNewConnectionAsync(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:116:18) 在MongoStore(/home/shaishab/Project/Open-Source/BS-Commerce/node_modules/connect-mongo/src/index.js:95:26) 在module.exports(/home/shaishab/Project/Open-Source/BS-Commerce/config/express.js:101:10) 在对象。 (/home/shaishab/Project/Open-Source/BS-Commerce/server.js:31:38) 在Module._compile(module.js:413:34) 在Object.Module._extensions..js(module.js:422:10)
var session = require('express-session'),
MongoStore = require('connect-mongo')(session),
mongoose = require('mongoose');
var db = mongoose.connect('dbUrl');
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new MongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
任何人都可以帮助我吗?
答案 0 :(得分:16)
最后我发现错误发生了!! 我发布这个答案因为它可能会帮助别人。
更新mongoose
和connect-mongo
版本时出现问题。
需要更新:
MongoStore = require('connect-mongo')(session)
和
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new MongoStore({
mongooseConnection: db.connection,
collection: config.sessionCollection
})
}));
主要问题出在MongoStore({db: db.connection.db
而非使用
db: db.connection.db
现在使用
mongooseConnection: db.connection
解决了我的问题:)
答案 1 :(得分:0)
由于我没有db variable
,我的解决方案是:
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost/chester');
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({mongooseConnection: connection})
}));
希望有所帮助