Node.js / MongoDB:如何使用module.exports将localhost数据库url传递给server.js文件?

时间:2016-01-28 11:18:22

标签: javascript node.js mongodb express

我在localhost上使用mongoose连接数据库时出现问题。

在我的server.js文件中,我有:

var express     = require('express');
var app         = express();                        //Create our app with express
var mongoose    = require('mongoose');              //Mongoose for mongoDB
var database    = require('./config/database.js');  //Load the database config

...

//Configuration =====================
mongoose.connect('database.url');   //Connect to mongoDB database

...

在我的database.js文件中,我有:

// Config/database.js

module.exports = {
url : 'mongodb://127.0.0.1:27017/test'
};

我在node.js命令提示符中遇到的错误是:

events.js:141
  throw er; // Unhandled 'error' event
  ^

Error: failed to connect to [database.url:27017]
at null.<anonymous> (C:\*filepath*\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:540:25)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (C:\*filepath*\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:140:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (C:\*filepath*\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection.js:478:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1256:8)

当我使用mongodb://127.0.0.1:27017 / test代替database.url时它运行正常。

我目前在Windows 10上使用node.js v4.2.6和mongodb 3.2。

如何让module.exports将url传递给server.js?

2 个答案:

答案 0 :(得分:5)

删除'',因为现在您尝试使用网址'database.url'连接到mongodb,但您需要使用包含正确网址url的{​​{1}} database属性}

mongodb://127.0.0.1:27017/test

答案 1 :(得分:0)

你试过用语音标记吗?

mongoose.connect('database.url');

正在尝试连接到地址&#39; database.url&#39;

mongoose.connect(database.url);

将获取数据库的