mongoose.connect在nodejs中给出错误

时间:2014-09-29 07:14:58

标签: node.js mongoose

我正在使用node连接到mongoose数据库,但是当我运行代码时,它会给出错误:

Uncaught TypeError: undefined is not a function
  (anonymous function)  server.js:13

以下是我在server.js中运行的代码

var express= require(['express']);
var bodyParser = require(['body-parser']);
var cookieParser = require(['cookie-parser']);
var expressSession = require(['express-session']);
var mongoose = require(['mongoose']);

var mongoStore = require(['connect-mongo'])({session: expressSession});
require(['./models/users.js']);
mongoose.connect('mongodb://localhost/userregistration');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views',__dirname + '/views');
app.set('view engine','html');

app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
    secret: 'SECRET',
    cookie: {maxAge:60*60*1000 },
    store: new mongoStore({
        db: mongoose.connection.db,
        collection: 'sessions'
    })

}));

require('./routes')(app);
app.listen(80);

查看日志,代码在以下位置给出错误:

mongoose.connect('mongodb://localhost/userregistration');

3 个答案:

答案 0 :(得分:0)

我想你忘了要求快递。

以下是示例

ExpressSession

app.use(express.session({
  secret: 'SECRET',
  cookie: {maxAge:60*60*1000 },
  store: new mongoStore({
    db: mongoose.connection.db,
    collection: 'sessions'
  })
}));

答案 1 :(得分:0)

connect-mongo有一个使用Mongoose连接的特殊选项,请尝试使用:

store: new mongoStore({
    mongoose_connection: mongoose.connection,
    collection: 'sessions'
})

如果没有解决问题,请发布更多信息(例如完整堆栈跟踪以及您正在运行的实际代码,因为那些require&# 39;看起来不对。)

答案 2 :(得分:0)

// Replace 'db' by  'mongooseConnection '

app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge: 60 * 60 * 1000},
store: new mongoStore({
    mongooseConnection: mongoose.connection,
    collection: 'sessions'
  })
}));