Tuesday 14 March 2017

Declare session with express node.js and mongoose

I'm doing an application with Node.js, Express, MongoDB (mongoose), I'm trying to make the database connection in a separate file from server.js, but I'm having a hard time with connect-mongo.

First in my server.js I had this:

/* jshint esversion: 6 */
'use strict';
let express = require('express');

const db = require('./app/config/db');
const routes = require('./app/routes/routes');
const users = require('./app/routes/users');

let app = express();

const conn = db.connect();

app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'hbs');

...

app.use('/', routes);
app.use('/users', users);

app.listen(3000);

module.exports = app;

This only handle the application routes, and the application server, then I had the next folder structure for my project:

myApp
|___app
    |___bin
    |___config
        |___credentials.js
        |___db.js
    |___controllers
    |___routes
    |___views
|___node_modules
|___package.json
|___server.js

Welll insidde config folder I had two javascripts that handle the connection to the database, in the credentials.js literally only had the credentials for the access of the database.

Then my problem is inside the db.js, next I show you the file:

/* jshint esversion: 6 */
'use strict';
let mongoose = require('mongoose'),
    async = require('async'),
    express = require('express');

const credentials = require('./credentials');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

let db = mongoose.connection,
    app = express();

exports.connect = function(done){
   const connection = mongoose.connect(credentials.host, credentials.database, credentials.port, credentials.db);

   db.on('error', (error =>{
       console.log("Error estableciendo la conexion");
       process.exit(1);
   }));

   db.on('open', (argv)=>{
       db.db.listCollections().toArray((err, collections)=>{
           collections.forEach(x => console.log(x));
       });
   });

   /* Define sessions in MongoDB */
   app.use(session({
       secret: credentials.sessionSecret,
       store: new MongoStore({ dbPromise: db })
   }));
}

I got the next error: Error with nodemon server.js

Do you know how to initiate connect-mongo using this project structure?

In advance thank you!



via Juan Carlos León

No comments:

Post a Comment