【问题标题】:using redis in mongodb在mongodb中使用redis
【发布时间】:2013-08-29 16:01:07
【问题描述】:

我有一个默认的 Express 应用,我的路由 index.js 文件如下所示:

var user = require('../models/user');

exports.index = function(req, res){
  res.render('index', { title: 'Express', object: obj });
};

现在,假设在我的 app.js 文件中,client 对象是连接到我的 redis 服务器的 redis 客户端,我希望能够在我的用户模型中使用该客户端对象,例如避免重复登录尝试。我怎样才能在我的用户模型中访问该对象?这是该模型的代码

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
  email:    { type: String, required: true, index: { unique: true } },
  password: { type: String, required: true },
  name:     { type: String, required: true }
});

var User = mongoose.model('User', userSchema);

exports.canLogin = function(mIn, pIn, next){
  User.findOne({
    email: mIn
  }, function(err, user){
    if(!err){
      if(user.password == pIn)
        next(true);
        else next(false);
    } else next(false);
  });
};

【问题讨论】:

  • 我不关注你的问题以及redis适合的地方。
  • 假设在我的 canLogin 函数中我想检查 redis 中的某些内容。如何从那里访问“客户端”对象?
  • 您的“客户”在会话中吗?
  • client 对象是在哪里创建的?在一个模块中,导出? canLogin 只是 JavaScript,所以我不遵循你想要做的事情。这似乎与 MongoDB 没有任何联系。

标签: node.js mongodb mongoose node-redis


【解决方案1】:

如果你想将你的客户端存储在会话中,你可以使用connect-redis 来设置会话存储,就像这样

var express = require('express');
var app = express();
var RedisStore = require('connect-redis')(express);

app.use(express.cookieParser());
app.use(express.session({
  store: new RedisStore({
    host: 'localhost',
    port: 6379,
    db: 2,
    pass: 'RedisPASS'
  }),
  secret: '1234567890QWERTY'
}));

现在,您可以像这样req.session.WHATEVER 访问会话

(And you can do the same thing with mongo.)

如果你在处理请求时只是想要一些redis存储可用,你可以直接使用node_redis。 github上有很多例子

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 2011-10-17
    • 1970-01-01
    • 2012-04-12
    • 2012-05-28
    • 1970-01-01
    • 2011-07-20
    • 2020-04-22
    • 2017-03-08
    相关资源
    最近更新 更多