无法使用mongoose连接到MongoDb。 MongoDB安装在我的本地系统中

我不能使用mongoose连接到MongoDb。 我已经在我的本地系统中安装了MongoDB

//Import the mongoose module var mongoose = require('mongoose'); //Set up default mongoose connection`enter code here` var mongoDB = 'mongodb://localhost/my_database'; mongoose.connect(mongoDB, { useMongoClient: true }); //Get the default connection var db = mongoose.connection; //Bind connection to error event (to get notification of connection errors) db.on('error', console.error.bind(console, 'MongoDB connection error:')); module.exports = mongoose.connection; 

得到错误:

 // MongoDB connection error: { MongoError: failed to connect to server [localhost:27017] on first connect 

你用mongod命令启动mongoDb吗?也许用mongod --port 12345在不同的端口上运行它mongod --port 12345

哈雷什,你需要testing你的代码,更具体地说,你的Mongoose和Mongo之间的连接。 Mongoose只是一个库,它不会自动连接到Mongo,这就是为什么你有上面的代码告诉它这样做,但你需要testing。

在任何你称为这个项目的根上创build一个testing目录。 在testing文件夹内部,创build一个test_helper.js文件。 在里面,你要写上面的代码,但是用这种方式将它重构成ES6模型。

 //Import the mongoose module const mongoose = require('mongoose'); //Set up default mongoose connection`enter code here mongoose.connect('mongodb://localhost/project_test'); mongoose.connection .once('open', () => console.log('Good to go!')) .on('error', (error) => { console.warn('Warning', error); }); 

希望这可以帮助。