【问题标题】:Should I use information stored in a cookie for indexing purposes?我是否应该将存储在 cookie 中的信息用于索引目的?
【发布时间】:2017-11-28 03:07:39
【问题描述】:

我正在创建我的第一个主要应用程序,并且我想到了一种优化查询性能的方法。我不确定我是否应该接受它。

这是我的方法的描述。

每次创建用户帐户时,都会为该用户分配一个介于 1 到 10 之间的随机数,该随机数存储在他们的用户文档中。该号码称为号码ID。用户架构如下所示:

let User = new Schema({

/// I left out all the other fields for clairty sake
numberId: {
          type: Number,
          default: Math.floor(Math.random() * 11),
          index: true
    }
}

每次用户创建博文和帖子时,都会在该博文和帖子的文档中引用他们的 number-Id。这是为了通过索引用户 number-id 来加快查询速度。这是一篇博文的文档在 MongoD 中的样子:

{ 
   "title": "my Blog Post",
   "_id": "ObjectId("594824b2828d7b15ecd7b6a5")",
   /// Here is the numberId of the user who posted the blogpost, it is added 
   /// to the document of the blogpost when it is created.
   "postersNumberId": 2
   /// the Id of the user who posted the blogpost
   "postersId": "59481f901f0c7d249cf6b050"
}

假设我想获取特定用户的所有博文。我可以通过使用相关用户的 number-Id 作为索引来更快地优化我的查询,因为他们发布的所有博客文章和评论帖子都引用了他们的 number-Id。

 BlogPost.find({postersId: user_id, postersNumberId: user.numberId});

似乎这种方法保证我将用户编号-id 存储在 req.user 中,以便在我需要它以优化查询时随时可用。所以这意味着我必须通过护照将用户数据存储在 cookie 中:

passport.serializeUser(function(user, done){
    done(null, user._id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function (err, user){
        if (err || !user) return done(err, null);
        done(null, user);
    });
});

鉴于这种方法,我现在可以使用 cookie 中存储的所有信息,尤其是 numberId,来优化检索用户创建的 cmets 和博客文章的查询:

BlogPost.find({postersId: req.user_id, postersNumberId: req.user.numberId});

但是,我使用 json-web-tokens 来验证用户而不是 cookie。因此,除了使用 JWT 进行身份验证之外,我还必须使用 cookie 来存储 number-Id 以用于索引目的。但是,我听说使用 cookie 不利于可扩展性,因此我担心将用户编号 ID 存储在 req.user 中最终会影响性能。

我应该继续使用这种方法,还是不应该?对性能有何影响?

【问题讨论】:

    标签: mongodb cookies mongoose query-performance json-web-token


    【解决方案1】:

    除了身份验证JWT还有一个payload,可用于在生成的令牌本身内存储附加信息:

    var jwt = require('jsonwebtoken');
    
    var token = jwt.sign({
        data: {
            numberId: 7
        }
    }, 'jwtSecret', {
        expiresIn: '1h'
    });
    

    检索:

    jwt.verify(token, 'jwtSecret', function(err, decoded) {
        if (err) {
            console.log(err)
        } else {
            console.log(decoded);
            //{ data: { numberId: 7 }, iat: 1498350787, exp: 1498354387 }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多