3

when trying to connect to mongo db from the project directory i get this

/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:133 throw err; ^ MongoError: cannot connect to server at Collection.listIndexes (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1712:11) at indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1531:25) at Db.indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1498:44) at ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1003:8) at Db.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:982:44) at ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1772:13) at Collection.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1760:44) at connectionReady (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:141:27) at Db.collection (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:425:20) at initWithNativeDb (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:207:20) at process._tickCallback (node.js:355:11) at Function.Module.runMain (module.js:503:11) at startup (node.js:129:16) at node.js:814:3

managed to connect using a simple app (code below)

*

var MongoClient = require('mongodb').MongoClient;
    // Connect to the db
    MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
      if(!err) {
        console.log("We are connected");
      }
    });

*

the main node file of the app in question code is below:


var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')({session: expressSession});
var mongoose = require('mongoose');
require('./models/users_model.js');
var conn = mongoose.connect('mongodb://localhost:27017/stressfullproject');
var app = express();
app.engine('html', require('ejs')._express); 
app.set('views', './site' + '/views');        
app.set('view engine', 'html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
    secret: 'stress',
    cookie: {maxAge: 60*60*1000},
    store: new mongoStore({
        db: mongoose.connection.db,
        collection: 'sessions'
    })
}));
require('./routes/routes')(app);
app.listen(80);

*

my defined schema

 *var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var UserSchema = new Schema({
    username: { type: String, unique: true },
    email: String,
    hashed_password: String
})
mongoose.model('User', UserSchema)*

because i can connect with the other app, im thinking its an issue with one of my modules? ive searched all over.

thanks in advance

1
  • could you give the full stack trace please. Commented Nov 23, 2015 at 21:32

4 Answers 4

2

My best guess is that you are using two modules namely MongoClient and mongoose both are trying to connect to port 27017. Now in this race only one will win and will lock that port. If you try and bind to that port it will give you an error, similar to the one you are getting above. My suggestion, don't use MongoClient. use only mongoose. There is a lot of help available for mongoose and many video tutorials on youtube use it. If that doesn't help let me know.

Let's prep you up with some code shall we. I don't use MongoClient now, but when I used to I wrote this code, see of it works. If it doesn't please paste the stacktrace.

var MongoClient=require('mongodb').MongoClient,

server=require('mongodb').Server;

var mongoclient=new MongoClient(new server('localhost',27017));

mongoclient.connect('mongodb://localhost:27017/course',function(err,db)
{
    if(err) throw err;
    //var db=mongoclient.db('course');
    var query={'grade':100};

    db.collection('grades').findOne(query,function(err,doc)
        {
            if(err) throw err;
            console.dir(doc);
            db.close();
        });
});
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for your help; I am not running the two modules at the same time. This issue has been present long before I created the 'small test module'. I only created the test module and ran it separately in order to see if a connection would be made, hopefully ruling out an issue with mongod server.
so your mongod server is running fine? mongod --dbpath ~/data/db opens up a connection??
Make sure your port 27017 is freed up. by running netstat -tulpn
Better than no error right? now let's debug it and see what happens? Did you change the name of collection and DB? Make sure you get some result when you run the same query in mongo console. If that is there you should be getting results
mongod server is running fine. it waits for a connection and opens one when 'mongo' cmd is used in another terminal.
|
2

i found the answer in another stack overflow post here

the problem was that the session (or something else outside of mongoose) was trying to connect to the database BEFORE mongoose established a connection.

Comments

0

Either one of two issues - either you are calling an undefined schema (mongoose) or you have a function requiring next but next is undefined. I've run into this problem many times and it's documented lack of error handling with mongoose. You need to define some error handling early in your app.js file.

1 Comment

i have defined the schema in another module: (code added above). ill have to get back to you on the 'next' issue
0

Mongodb version v4.2.6 --- Node.js version: v14.2.0

first, make sure you are running mongodb local server, check for exsiting db by bellow command:

show dbs

output: enter image description here

Now I want to connect with database tours-test

first install mongooes by command

npm i mongoose

Now in you connection.js

const mongoose = require('mongoose');

const conStr = 'mongodb://localhost:27017/tours-test';
mongoose
  .connect(conStr, {
    usedNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => console.log('DB connection successful'));
// remember mongoose.connect() return Promise

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.