【问题标题】:Declare session with express node.js and mongoose使用 express node.js 和 mongoose 声明会话
【发布时间】:2017-08-05 15:49:32
【问题描述】:

我正在使用 Node.js、Express、MongoDB (mongoose) 做一个应用程序,我正在尝试在 server.js 的单独文件中建立数据库连接,但我很难连接 -蒙哥。

首先在我的 server.js 中我有这个:

/* 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;

这仅处理应用程序路由和应用程序服务器,然后我的项目就有了下一个文件夹结构:

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

Welll insidde config 文件夹我有两个 javascripts 来处理与数据库的连接,在 credentials.js 中实际上只有访问数据库的凭据。

那我的问题是在 db.js 里面,接下来我给你看文件:

/* 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 })
   }));
}

我得到了下一个错误: Error with nodemon server.js

你知道如何使用这个项目结构来启动 connect-mongo 吗?

顺便说一下,在 credentials.js 文件中,我将 Bluebird 设置为我的 Promise 库。

提前谢谢你!

【问题讨论】:

  • db.on('open'...) 被调用了吗?
  • @MananVaghasiya 你好。是的,我实际上有一个 console.log 告诉我连接是否建立,所以我真的不知道是什么问题。
  • 问题肯定是“db”没有被承诺。你确定 mongoose.connection 是一个承诺吗?
  • @MananVaghasiya 你是对的,这是新快速版本的问题,我将方法更改为简单连接。 mongoose.connection(uri)

标签: javascript node.js express mongoose


【解决方案1】:

问题是,就像@MananVaghasiya 所说,我的变量 db 不是 Promise,这是 mongoose 项目中的一个错误,所以我将连接类型更改为与 mongoose 的基本 uri 连接,然后在查询之后登录时我设置了会话。

此时的代码如下所示,感谢您的宝贵时间。

module.exports.login = (req, res)=>{
    const mail = req.body.mail.replace(/^\s\s*/, '').replace(/\s\s*$/, ''),
          password = req.body.password;

    user.findOne({$and:[{'mail' : mail}, {'password': password}]}, (err, user)=>{
        if(err){
            res.send(err);
        } else {
            /* Define sessions in MongoDB */
           app.use(session({
               secret: credentials.sessionSecret,
               store: new MongoStore({ mongooseConnection: db }),
               saveUnitialized: true,
               resave: false,
               cookie:{
                   path: "/"
               },
               name: user.role
           }));
           return user;
       }
   });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2011-07-06
    • 1970-01-01
    • 2011-10-12
    • 2021-07-08
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多