草庐IT

node.js - MongoError : cannot establish topology capabilities as driver is still in process of connecting at Server. 功能

coder 2023-10-27 原文

我正在尝试通过 mongoose.connect 连接到 mongoDB,但我仍然收到错误:

/Users/Documents/Business/01000100/node_modules/connect-mongo/lib/connect-mongo.js:133
          throw err;
                ^
MongoError: cannot establish topology capabilities as driver is still in process of connecting
    at Server.capabilities

auth_server.js:

    var express         = require('express')
var body_parser     = require('body-parser')
var cookie_parser   = require('cookie-parser')
var express_session = require('express-session')
var mongo_store     = require('connect-mongo')({session:express_session})
var mongoose        = require('mongoose')
var morgan          = require('morgan')
var port            = 8080

//MODELS
require('./models/user_model.js')

//CONFIG
mongoose.connect('mongodb://localhost/db')

var app = express()

//VIEW ENGINE
app.engine('.html', require('ejs').__express)
app.set('views', __dirname + '/views')
app.set('view engine', 'html')

//MIDDLEWARE
app.use(morgan('dev'))//logging requests
app.use(body_parser.urlencoded({extended: true}));
app.use(cookie_parser())
app.use(express_session({
    secret: '2!H$,Br2&1XW74zpd897ytf lbph=-0987654edfvbn5Q4AQ0]k7XX2Plh915ZV2)0)2DvHK}4KA"^6J!TY;x4z04',
    cookie: {maxAge: 60 * 60 * 1000},
    store: new mongo_store({
        db: mongoose.connection.db,
        collection: 'sessions'
    }),
    resave: false,
    saveUninitialized: false
}))

//ROUTES
require('./routes')(app)

//START
app.listen(port)
console.log('Santa is listening on ' + port)

有谁知道导致此问题的原因或解决方法?我花了很多时间研究它,但我似乎仍然无法找到解决方案。非常感谢您。

最佳答案

有些东西,很可能是 session 存储信息,它不直接使用 mongoose 方法,而是在连接建立之前尝试访问数据库。 mongoose 方法本身将其隐藏起来并将操作“排队”,直到实际建立连接为止。

将所有应用程序启动包装在“连接”事件中以确保已建立连接:

//CONFIG
mongoose.connect('mongodb://localhost/db');   // Does not wait for connection here

var app = express();

mongoose.connection.on("connect",function(err) {   // But this waits for connection

    // All Setup here - But especially this

    app.use(express_session({
        secret: '2!H$,Br2&1XW74zpd897ytf lbph=-0987654edfvbn5Q4AQ0]k7XX2Plh915ZV2)0)2DvHK}4KA"^6J!TY;x4z04',
        cookie: {maxAge: 60 * 60 * 1000},
        store: new mongo_store({
            db: mongoose.connection.db,
            collection: 'sessions'
        }),
        resave: false,
        saveUninitialized: false
    }))


    //START
    app.listen(port)
    console.log('Santa is listening on ' + port)

})

关于node.js - MongoError : cannot establish topology capabilities as driver is still in process of connecting at Server. 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31648043/

有关node.js - MongoError : cannot establish topology capabilities as driver is still in process of connecting at Server. 功能的更多相关文章

随机推荐