简体   繁体   中英

can't connect to MongoDb using mongoose. MongoDB installed in my local system

I cant connect to MongoDb using mongoose. I have installed MongoDB in my local system

//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;

getting the error:

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

您是否使用命令mongod启动mongoDb也许使用mongod --port 12345在其他端口上运行了它

Hareesh, you need to test your code, more specifically, your connection between Mongoose and Mongo. Mongoose is just a library, it does not automatically connect to Mongo which is why you have the code above to tell it to do so, but you need to test that.

Create a test directory at the root of whatever it is you called this project. Inside of the test folder, create a test_helper.js file. Inside of it, you are going to write the code above, but refactor it into the ES6 model in this manner.

//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);
});

Hope this helps.

I had the same problem. Seemingly using localhost in your connection string is the issue. Best just use 127.0.0.1 in place of localhost . In linux both work well but windows the localhost has issues

Example:

const DB_URL="mongodb://127.0.0.1/<db_name>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM