3
votes

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

4
could you give the full stack trace please.Saras Arya

4 Answers

2
votes

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();
        });
});
2
votes

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.

0
votes

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.

0
votes

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