Express在使用mongodb的时候app配置出错
//settings.js
module.exports={
cookieSecret:"xxxx",
db:"dbname",
host:"localhost",
}
//app.js
var express = require("express");
var settings = require("./settings");
载入connect-mongo的出错写法:
var MongoStore=require("connect-mongo")(express);
app.use(express.session({
secret:Settings.cookieSecret,
key:Settings.db,
cookie:{maxAge:1000*60*60*24*30},//30 days
store:new MongoStore({
db:Settings.db
})
}));
启动后报错:TypeError: Cannot read property 'Store' of undefined
以上是 express<4的写法
express 4.0之后(包含4.0)写法例如以下:
var session = require("express-session");
var MongoStore=require("connect-mongo")(session);
app.use(session({
secret:settings.cookieSecret,
store:new MongoStore({
db:settings.db
})
});
package.json配置例如以下
{
"name": "dbTest",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~4.2.0",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"mongodb":"*",
"connect-mongo":"*",
"express-session":"*"
}
}
//假设文件夹下没有运行过npm install请在添加mongodb,connect-mongo,express-session之后在package.json文件夹下运行一下npm install
以上是express中对mongodb的配置,假设你本地没有装mongodb的数据库请到http://www.mongodb.org/downloads下载安装。