无法将Mongodb连接到Node.js,MEAN-stack

时间:2016-01-09 15:41:55

标签: javascript node.js mongodb mongoose mean-stack

我是Mac用户,而且我对MEAN-stack非常陌生。我试图将Mongoose与我的Node.js连接,但它总是显示此错误

events.js:141
  throw er; // Unhandled 'error' event
  ^ 
Error: failed to connect to [undefined:27017]
at null.<anonymous> (/Users/toeysk/Desktop/testwebrtc.git/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:556:25)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (/Users/toeysk/Desktop/testwebrtc.git/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:156:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/Users/toeysk/Desktop/testwebrtc.git/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:534:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at connectErrorNT (net.js:996:8)
at doNTCallback2 (node.js:452:9)
at process._tickCallback (node.js:366:17)

我可以在终端中正常使用Mongoose和Mongodb。

这是我的 server.js

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var mongoose = require('./config/mongoose'); //connect DB
var express = require('./config/express');

var db = mongoose();
var app = express();
app.listen(3000);

module.exports = function(){
    require('../app/routes/index.routes')(app);
    require('../app/routes/user.routes')(app);
};

module.exports = app;

它叫 mongoose.js

var config = require('./config');
var mongoose = require('mongoose');

console.log('Mongoose.js');
console.log(config);

module.exports = function(){

    mongoose.set('debug', config.debug);

    var db = mongoose.connect(config.monoUri);

    console.log('Call User Model');
    require('../app/models/user.model');

    return db;
}; 

然后调用 config.js development.js

/////config.js/////

module.exports = require('./env/' + process.env.NODE_ENV + '.js');

/////development.js/////

module.exports = {
    debug: true,
    mongoUri: 'mongodb://localhost/webrtc',
    sessionSecret: 'dev_secret_key'
};

请帮忙。我一直试图调试这个约2天,我没有什么新东西。什么都错过了?

2 个答案:

答案 0 :(得分:0)

错误指向您:

Error: failed to connect to [undefined:27017]

所以数据库的位置有问题,看起来主机名是未定义的。

这是您的连接代码:

var db = mongoose.connect(config.monoUri);

在这里你的配置:

mongoUri: 'mongodb://localhost/webrtc'

你能发现连接代码中的拼写错误吗?它说monoUri,而不是mongoUri

答案 1 :(得分:0)

你能做到吗

npm install mongoose

并发布

的输出
ps -ef | grep mongod

您正在运行节点的计算机上的所有内容。对于其余的答案,这将有很长的路要走。

同样遵循简单的示例代码 - https://github.com/mongodb/node-mongodb-native#introduction,替换数据库名称和集合名称并在节点上运行

node sample.js