1

I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.

Here is my code:

dbtest.js

    var express  = require('express');
    var app      = express();                               // create our app w/ express
    var mongoose = require('mongoose');                     // mongoose for mongodb
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    var options = {
          useMongoClient: true,
          autoIndex: false, // Don't build indexes
          reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
          reconnectInterval: 500, // Reconnect every 500ms
          poolSize: 10, // Maintain up to 10 socket connections
          // If not connected, return errors immediately rather than waiting for reconnect
          bufferMaxEntries: 0
};



    var Todo = mongoose.model('Todo', {
        text : String
    }, 'test');

    var status = {
    "status": "not connected"
    };

    app.get('/api/todos', function(req, res) {

            mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
    {
              if (err) {
              res.json(status);
            } else {
                res.json('Connected');
            }    
    });  
    });

    app.listen(8080);
    console.log("App listening on port 8080");

When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.

JSON Message

I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.

Any suggestions are appreciated.

4
  • Then res.json({ err }) instead of your res.json(status) and actually look at what the error is. Commented Nov 9, 2017 at 5:38
  • This is the error after the code change as per your comment: {"err":{"state":2}} Commented Nov 9, 2017 at 6:01
  • Add in console.log(err) and that output will show on the console. Paste the "text" ( NOT a screenshot ) into your question. There will be more detail than what you are telling anyone. Commented Nov 9, 2017 at 6:04
  • Message is: "Error: Trying to open an unclosed connection." then lots of stack traces. Commented Nov 9, 2017 at 7:37

3 Answers 3

1

Your first mongoose.connect() argument lacks username / password combination:

mongoose.connect('mongodb://username:[email protected]:27017/exampleDB');
Sign up to request clarification or add additional context in comments.

1 Comment

I can actually connect to MongoDB compass without supplying a username and password so I wonder what can be wrong here.
0

Try to connect db first before doing any action. Once it connected try to use inside your custom function. Below code will helps you to test local database

const express = require('express');
const app = express();
const port = 3000;
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/dbname', { useMongoClient: true });
mongoose.connection.on('connected', () => {
  console.log('Connected to database ');
}); 
mongoose.connection.on('error', (err) => {
  console.log('Database error: '+err);
});


// Start Server
app.listen(port, () => {
  console.log('Server started on port '+port);
});

Check your cmd window to see console.

2 Comments

For local database MongoDB compass will accept without username and password by default with default port; FOr other data base you have to provide
tried your code in a separate js file, but it only returned me the Server started log. No log on 'connected' or 'error'.
0

For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :

mongodb://USER:[email protected]/DB?authSource=admin

You don't need to provide the port 27017, because it's the default one for mongodb.

The trick here is to add with 'authSource=admin' for enabling the authentication.

Documentation : https://docs.mongodb.com/manual/reference/connection-string/#examples

Comments

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.