I'm just learning MongoDB and Node.js. I'm doing this really simple exercise from a video in which I try to connect my node.js app to my MongoDB, and I'm getting this error:
{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }
Before all that, I've configured a database on mongo, and have tested running some commands on terminal:
$mongod (everything ok)
$mongo (everything ok)
..and then I've created a database called 'products' and added some products to it. When I hit:
db.products.find()
It returns:
{
"_id": ObjectId("55b2b27d7f9f84490b8a9170"),
"name": "beer",
"description": "belgian craft beer",
"price": 20
}
{
"_id": ObjectId("55b2b2c27f9f84490b8a9171"),
"name": "whisky",
"description": "scotch blended 18 years old",
"price": 150
}
{
"_id": ObjectId("55b2b3e47f9f84490b8a9172"),
"name": "cachaça",
"description": "typical brazilian cachaça",
"price": 10
}
{
"_id": ObjectId("55b2b4087f9f84490b8a9173"),
"name": "water",
"description": "water from the swiss alps",
"price": 5
}
{
"_id": ObjectId("55b2b2617f9f84490b8a916f"),
"name": "wine",
"description": "red porto wine",
"price": 80,
"tags": [
"porto",
"sweet",
"wine"
]
}
My app.js:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/products');
var db = mongoose.connection;
db.on('error', function(err){
console.log('Erro de conexao.', err)
});
db.on('open', function () {
console.log('Conexão estabelecida.')
});
db.on('disconnected', function(err){
console.log('Desconectado')
});
And my package.json:
{
"name": "aula-mongoose",
"version": "0.0.1",
"description": "aula sobre mongoose",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node.js",
"mongodb"
],
"author": "Guga",
"license": "WTFPL",
"dependencies": {
"mongoose": "^4.1.0"
}
}
I've read lots of posts about this, even threads here. But I couldn't find out what is wrong here.
EDIT:
Accidentally I tried to connect to $mongod while it was already running and I was prompted with this error:
errno:48 Address already in use for socket: 0.0.0.0:27017
So I changed this line in my app.js to:
mongoose.connect('mongodb://0.0.0.0:27017/products');
And it worked. But I have no idea why. Anyone?