我有一个带有基本CRUD 操作
的简单 API,其中一个用户可以有多个任务,一旦用户登录就可以更新、删除、添加和获取所有任务。
我使用 MongoDB
和 mLab
作为我的主要数据存储来存储用户和任务模式的文档。
我想在我的应用程序中实现 Redis 缓存
(仅用于学习目的),我能想到的一个用例是在我为特定用户(在主页上)登录时获取任务时实现它因为 getAllUserTasks
在发生任何删除/更新/添加时经常被使用和调用。
截至目前,该应用程序可与 MongoDB
一起正常工作,并且文档已正确反射(reflect)在 mLab
中。
现在来到 Redis 部分,我有一个问题,我应该如何构建我的 Redis 数据库。首先,让我发布到目前为止我的应用程序中的内容:
用户架构:
const userSchema = new Schema({
userName: { type: String, unique: true, required: true },
hashPassword: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
userAge: { type: Number, required: true },
userDetails: { type: String, required: true },
userCreatedOn: { type: Date, default: Date.now }
});
任务架构:
const taskSchema = new Schema({
//Below is userAssigned which is ref for above User document.
userAssigned: { type: Schema.Types.ObjectId, ref: User},
taskDesc: { type: String, required: true },
taskCreatedOn: { type: Date, default: Date.now },
taskDueDate: { type: Date, required: true }
});
getAllUserTasks 函数:
async function getAllUserTasks(userParam) {
return await Task.find({ userAssigned: userParam.userId })
.lean()
.sort({ taskDueDate: "asc" });
}
现在 getAllUserTasks
返回一个包含用户所有任务的 Array
。
我用谷歌搜索了一下,发现我可以为我的 Redis 数据库使用 https://redislabs.com/
。现在我应该如何构建我的 Redis 数据库以高效地获取任务? 1. 我是否应该将上面的模式复制到 Redis 数据库,我的任务文档将保存在那里。
2. 我是否应该有一个像“任务”这样的 key
而 value
将是我从 getAllUserTasks
中的 .find 获取的任务数组> 打电话。如果是这种情况,我将如何确保一旦任务被删除/更新/添加,Redis 数据库将相应更新?下面仅供引用是我的更新/创建/删除方法:
创建任务
async function createTask(userParam) {
if (await User.findOne({ _id: userParam.userAssigned })) {
const task = new Task(userParam);
await task.save();
} else {
throw "User does not exist";
}
}
更新任务
async function updateTask(id, userParam) {
return await Task.findOneAndUpdate(
{ _id: id },
userParam,
{
new: true,
overwrite: true
},
function(err) {
if (err) return err;
}
);
}
删除用户任务
async function deleteUserTask(id) {
return await Task.findByIdAndRemove(id, function(err) {
if (err) {
return err;
}
});
}
由于我是 Redis 的新手,因此非常感谢任何帮助。谢谢!
最佳答案
您不必将所有数据存储到 Redis。缓存是一种捷径。有数据就好,没有也没关系。
调用 getAllUserTasks
时存储任务。 key 可以是用户 ID。值可以是具有标识标识的任务数组。
如果某人的任务发生变异,只需从redis中清除某人的任务。
getAllUserTasks(param) {
1. Find tasks from redis by user key.
2. If they exist, return them.
3. If not, get data from db and store them to redis.
4. Return data.
}
关于node.js - nodejs-express - 在主数据库上实现 Redis 缓存作为 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54357895/