Reputation:
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
Upvotes: 1
Views: 2665
Reputation: 743
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>"
Upvotes: 4
Reputation: 15413
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.
Upvotes: 0
Reputation: 161
Did you start mongoDb with the command mongod
Maybe run it on a differnt port with mongod --port 12345
Upvotes: 0