1

I'm having trouble connecting mongodb to my local machine. I'm new at this and can't seem to figure it out from the docs or other stackoverflow posts.

I have a database.js file, and I think my connection string is wrong:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
// I've tried this too:
// mongoose.connect('mongodb://localhost/test');
// mongoose.connect('mongodb://localhost:8080/test');

module.exports = {
    'url' : 'mongodb://localhost:27017/test'
}

I've got mongod running in one tab and shows 4 connections open - I don't know if it's this or the connection string.

Then in a 2nd tab, I've connected to a db called "test".

Lastly there's a very simple view. When I navigate to localhost:8080 (where process.env.PORT || 8080 is pointing to in server.js), it doesn't connect.

2 Answers 2

3

Try this

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');//Here test is my database

var Cat = mongoose.model('Cat', { name: String });

var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
  if (err) {
    console.log(err);
  } else {
    console.log('meow');
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Here is configuration file

{
    "db": {
        "connection": "mongodb://localhost",
        "name": "testdb"             
    }
}

Here is usage in code:

var dbUrl = config.get('db:connection') + '/' + config.get('db:name');
var db = mongoose.connection;

mongoose.connect(dbUrl, function(err) {
 //your stuff here 
});

Hope, it helps.

P.S. Could you please provide how you catch no connection to db?

1 Comment

I was mistaken. I thought the server.js was running w/nodemon but it crashed. user error!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.