node.js - 如何使用 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});
})
});
解决方案
推荐阅读
- javascript - 缩小地图时聚合的传单标记
- r - 错误:'\l' 是从 "' 开始的字符串中无法识别的转义
\l" - python - 为什么 Tesseract 不能正确识别文本?
- docker - 如何下载 npm 依赖项作为 Docker 构建的一部分
- attributeerror - AttributeError:“函数”对象没有属性“x0”
- bash - Bash 日期减法 +%H:%M:%S
- unity3d - 在 Unity 中重置字符位置不起作用
- node.js - RangeError:WebAssembly.instantiate():内存不足:wasm 内存
- html - 使用引导程序在容器内对齐步进器 div
- spring - 如何平衡正在运行的 Pod 上的共享表记录?