7

I'm studying Node.js and i can'y find any solution.. my consol send me many messages an one is more particulary strange : GET/signup - - ms - - has someone any idea about that ? Thanks in advance !

///////////////////////inclusion des librairies
 // 3 librairies pour gérer les messages flash
 var session = require('express-session');
 var cookieParser = require('cookie-parser');
 var flash = require('express-flash');
 //passerelle pour se connecter à node(node->bdd)
 var passport =require('passport');
 // stockage des sessions(id) et cookies côté serveur uniquement
 var mongoStore =require('connect-mongo')(session); // le session de express-session

//inclure al librairie  express
 var express = require('express');
// Inclusion de la librairie morgan (faire le lien avec la base de données)
var morgan = require('morgan');

// Inclusion de mongoose
 var mongoose = require('mongoose');

 //Inclusion moteur templates ejs
 var ejs = require('ejs');
  var engine =require('ejs-mate');
  // Inclusion de body parser pour les données des formulaires
  var bodyParser = require('body-parser');



  /////////////////////fin des librairies ///////////////

// stocker l'objet express dans une variable plus courte
 
 var app = express();



//inclure le fichier secret.js
var secret = require('./config/secret');
 ////////////connexion à la bd avec mongoose///
 
 mongoose.connect(secret.database, // voir pour création de db en ligne !!
 	{useNewUrlParser:true},
 	function(err){
 		if(err){console.log(err)
 		}else{
 			console.log('connexion OK');
 		}
 	});


/////////////////// gestion des Passerelles (middleware)/////////////////////////
app.use(express.static(__dirname + '/public')); // pour le style
app.use(morgan('dev'));
app.engine('ejs',engine);
app.set('view engine','ejs');
// les deux lignes ci-dessous pour récupérer les données des formulaires
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
// affichage messages flash et gestion des cookies
app.use(cookieParser());
app.use(session({
	resave :true,
	saveUninitialized:true,
	secret :secret.secretKey,
	store : new mongoStore({
		url:secret.database,
		autoReconnect:true })
}));

app.use(flash());

//authentification
app.use(passport.initialize());
app.use(passport.session());


////////////////définition du chemin des pages principales////////////////////////

var mainRoutes =require('./routes/main');
app.use(mainRoutes);

var userRoutes =require('./routes/user');
app.use(userRoutes);



//app.post()

//app.put()

//app.delete()

AND THE CONSOLE SAYS :

Le serveur est lancé sur le port3000 (node:7828) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead. connexion OK (node:7828) UnhandledPromiseRejectionWarning: MongoError: not authorized on admin to execute command { insert: "system.indexes", documents: [[{ns admin.sessions} {key [{expires 1}]} {name expires_1} {expireAfterSeconds 0} {unique false}]], ordered: true } at Function.MongoError.create (C:\Users\Utilisateur\Desktop\NODE\ECommerce\node_modules\connect-mongo\node_modules\mongodb-core\lib\error.js:31:11) at C:\Users\Utilisateur\Desktop\NODE\ECommerce\node_modules\connect-mongo\node_modules\mongodb-core\lib\connection\pool.js:497:72 at authenticateStragglers (C:\Users\Utilisateur\Desktop\NODE\ECommerce\node_modules\connect-mongo\node_modules\mongodb-core\lib\connection\pool.js:443:16) at Connection.messageHandler (C:\Users\Utilisateur\Desktop\NODE\ECommerce\node_modules\connect-mongo\node_modules\mongodb-core\lib\connection\pool.js:477:5) at TLSSocket. (C:\Users\Utilisateur\Desktop\NODE\ECommerce\node_modules\connect-mongo\node_modules\mongodb-core\lib\connection\connection.js:333:22) at TLSSocket.emit (events.js:182:13) at addChunk (_stream_readable.js:283:12) at readableAddChunk (_stream_readable.js:264:11) at TLSSocket.Readable.push (_stream_readable.js:219:10) at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17) (node:7828) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:7828) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. GET /login - - ms - - GET /login - - ms - - GET /login - - ms - - GET /signup - - ms - -

5 Answers 5

34

The npm module connect-mongo can't handle mongodb+srv:// connection strings. You'll have to use the older connection string types that start with mongodb://.

If you are using MongoDB Atlas I recommend to go to connect on the cluster view, then connect your application and then select Node.js version 2.2.12, not 3.0.

You probably also have to change the /test or /admin in your connection string to /TheNameOfYourDatabase with your database name there. (See radihuq's answer below)

Sign up to request clarification or add additional context in comments.

6 Comments

Tanks a lot ConstJS ! I didn't see your asweer before now. everything is working well !! Thanks again :)
Glad it worked! @cessother Could you please mark it as answered? :)
I will do it with pleasure, but I have one more question : How do I do to mark it as answered ? :)
Click on the check mark beside the answer to toggle it from greyed out to filled in. This marks it as answered :)
been trying to solve this forever, this finally worked. thank you. To help others-- this also surfaces as: MongoError: Cannot do raw queries on admin in atlas
|
5

@ConstJS answer worked for me. Expanding on it a little bit -

If you're using Postman and your error looks like this:

"errmsg": "not authorized on admin to execute command { insert: [..] }, $db: \"admin\" }"

Note this specific part:

$db: \"admin\"

You'll want to change that to your DB name so go to your URI and find

mongodb.net:27017/admin

and change admin to your database name

2 Comments

This should be also an accepted answer. Thanks @Taslim
Thanks, I updated the answer and added a reference to your answer in my answer above :)
0

It appears you are trying to access MongoDB's admin database and insert something which is not allowed. I am assuming you are using a connection string like:

mongodb://mongodb0.example.com:27017/admin

Make sure you update the /admin piece to the database you want to connect to.

2 Comments

Hi Nick, thank you for your answer. I use this kind of connexion for mongodb Atlas : mongodb+srv://root:<password>@cluster0-zfgku.mongodb.net/test?retryWrites=true. I can add user, but no session id, that's strange. Maybe there is a problem withe the library "connect-mongo" ?
If you can access the DB to save a user, then the connection is okay. I think your issue is related to not passing the Mongoose connection to the session. I think you may want to look into reusing your connection. Look at the section "Re-use a Mongoose connection" here: npmjs.com/package/connect-mongo
0

This error is specific to the fact that you are passing a url mongo-connect doesn't know how to handle. Instead of the URL, you can pass the mongoose.Connection object and use the mongooseConnection property in the MongoStore options object.

new mongoStore({
  mongooseConnection: mongoose.connection,
  autoReconnect: true 
})

In order for this to work, you'll need to establish a connection first and then pass the mongoose.connection object to your mongoStore class.

 mongoose.connect(secret.database, {useNewUrlParser:true}, function(err) {
    if(err) { 
      console.log(err)
    } else {
      app.use(session({
        resave :true,
        saveUninitialized:true,
        secret :secret.secretKey,
        store : new mongoStore({
          url:secret.database,
          autoReconnect:true })
      }));
      console.log('connexion OK');
    }
});

There are more elegant ways to handle it but that should get you started.

Comments

0

It seems this error is generic, I was getting this error as my connection string didn't have the name of database:

"mongodb+srv://<username>:<password>@searchpractice0.rh7gx.mongodb.net/<NameOfDatabase>?retryWrites=true&w=majority";

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.