登录
注册
node.js 学习社区
nodejs+express mongodb连接出错?

QQHI123

2015-10-03 12:21

按照《node.js实例》上的代码书写,使用的IDE是webstorm10,mongodb是从

webstorm->settings下载的,然后webstorm直接下载到的project的node_moduels里面的,由于是用的express 4.13.1版本(书上的是3.0版本),所以有些代码参照网页上的做了一些更改:

在app.js里面session(session也是下载了的)是用的

var session=require('express-session');

var MongoStore=require('connect-mongo')(session);

app.use(session({

resave:false,//error

saveUninitialized: true,//error

secret: settings.cookie_secret,

key:settings.db,

cookie:{maxAge:1000*60*60*24*30},

store: new MongoStore({

db : settings.db,

})

}));

在package.json里面是这么写的:

{

"name": "myblog",

"version": "0.0.0",

"private": true,

"scripts": {

"start": "node ./bin/www"/*node ./bin/www*/

},

"dependencies": {

"body-parser": "~1.13.2",

"cookie-parser": "~1.3.5",

"debug": "~2.2.0",

"ejs": "~2.3.3",

"express": "~4.13.1",

"morgan": "~1.6.1",

"serve-favicon": "~2.3.0",

"mongodb":"~2.0.43",

"connect-mongo":"~0.8.2",

"express-session":"~1.11.3"

}

}

然后按照书中的要求实例化mongodb,在根目录新建了models->db.js,db.js里面写的是

var settings=require('./settings'),

Db=require('mongodb').Db,

Connection=require('mongodb').Connection,

Server=require('mongodb').Server;

module.exports=new Db(settings.db,new Server(settings.host.Connction.DEFAULT_PORT),{safe:true});

结果运行出错:

"C:\JetBrains\WebStorm 10.0.4\bin\runnerw.exe" C:\JetBrains\nodejs\node.exe bin\www

Fri, 02 Oct 2015 09:08:14 GMT myblog:server Listening on port 3000

c:\Users\Lenovo\WebstormProjects\myblog\node_modules\mongodb\lib\server.js:235

process.nextTick(function() { throw err; })

^

Error: connect ECONNREFUSED

at exports._errnoException (util.js:746:11)

at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)

Process finished with exit code 1

之前问过一位大神,他是app.use(session(里面))建议改为:

store: new MongoStore(settings.db);

之前的connect报错没有了,不过又有报错:

c:\Users\Lenovo\WebstormProjects\myblog\app.js:43 store: new MongoStore(settings.db);

^

SyntaxError: Unexpected token ;

at exports.runInThisContext (vm.js:73:16)

at Module._compile (module.js:443:25)

at Object.Module._extensions..js (module.js:478:10)

at Module.load (module.js:355:32)

at Function.Module._load (module.js:310:12)

at Module.require (module.js:365:17)

at require (module.js:384:17)

at Object.<anonymous> (c:\Users\Lenovo\WebstormProjects\myblog\bin\www:7:11)

at Module._compile (module.js:460:26)

at Object.Module._extensions..js (module.js:478:10)


Process finished with exit code 1

回复 · 1

发表回复

你可以在回复中 @ 其他人