首页 > 解决方案 > 如何使用 node.js 在 Redis 中同步 mongoDB 数据库的更改

问题描述

问题陈述如下:首先我使用后端 API 创建了一些帖子,然后在获取帖子时首先查看 Redis,如果存在与该帖子相关的密钥,然后我返回数据,否则我发送向 MongoDB 请求并获取所有这些帖子,然后将其保存到 Redis。现在我再次请求获取数据,然后正确地从 Redis 获取数据。但问题是,当我现在使用后端的 POST 请求添加另一个帖子然后再次更新我的 redis 时,它在 mongoDB 中成功创建,但是当我感染这些帖子时,我得到的是较旧的缓存帖子,而不是所有帖子,包括较新的帖子。

router.get('/posts',(req, res)=>{
  // check if any hashed data is there in redis 
  client.get('posts',(err, posts)=>{
    if(posts){
      // if yes then send it right away
      console.log('serving from redis ');
      return res.json({success: true, posts: JSON.parse(posts)});
    } else {
      //  if no then send the request and updated the redis with the new data 
      console.log('serving from mongoDB');
      Post.find({})
        .sort('-date')
        .populate('user', ['name', 'avatar', 'email'])
        .populate('profile')
        .exec((err, posts)=>{
          if(err){
            console.log(err);
            res.status(404).json({success: false, err});
          } 
          if(posts){
            // now update the redis cache       
            client.set('posts', JSON.stringify(posts));
            res.json({success: true, posts: posts});
          }
        })
      }
    });
});

以下是创建帖子和更新 redis 的代码:-


router.post('/create',passport.authenticate('jwt',{session: false}),(req, res)=>{
  // check if profile for the user exists or not 
  Profile.findOne({user: req.user.id})
    .then((proifle)=>{
      console.log(proifle);
      if(!profile){
        return res.json({success: false, msg: 'Please create the profile first'});
      } else {
        // create post 
        const newPost = new Post({
          profile: profile._id,
          user: req.user.id,
          title: req.body.title,
          description: req.body.description,
          requiredFunding: req.body.requiredFunding,
          date: Date.now()
        })
        newPost.save()
          .then((post)=>{
            console.log(post);
            // set post in the redis 
            client.set(JSON.stringify(post._id), JSON.stringify(post));
            res.json({success: true, post});
          })
          .catch((err)=>{
            console.log(err);
          })
      }
    })
    .catch((err)=>{
      console.log(err);
      res.status(404).json({success: false, err});
    })
});

标签: node.jsmongodbredismean-stackmern

解决方案


推荐阅读