[BUG]Nodejs index页个人信息栏目关注信息显示不正确
[BUG]Nodejs index页个人信息栏目关注信息显示不正确
### [BUG] Nodejs index页个人信息栏目关注信息显示不正确
描述
在我们的应用中,用户登录后会在首页(index页)看到个人信息栏目,其中包含关注的信息。但是最近发现这些关注信息有时会显示错误,即显示了其他用户的关注信息而不是当前登录用户的关注信息。
环境
- Node.js 版本: v14.17.0
- 框架: Express.js
- 数据库: MongoDB
复现步骤
- 用户登录系统。
- 跳转到首页(index页)。
- 查看个人信息栏目中的关注信息。
- 发现显示的不是当前用户的关注信息。
代码片段
假设我们有一个简单的用户模型 User
和一个关注列表模型 FollowList
,以下是可能存在问题的代码片段:
// 用户模型
const User = require('./models/User');
const FollowList = require('./models/FollowList');
router.get('/index', async (req, res) => {
try {
const user = await User.findById(req.user.id);
const followList = await FollowList.findOne({ userId: user._id });
// 这里可能是问题所在,没有确保返回的是当前用户的关注信息
res.render('index', {
username: user.username,
follows: followList.follows
});
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
});
分析
问题可能出在 FollowList.findOne()
查询中,没有明确地检查是否返回了正确的用户数据。如果数据库中存在多个用户的数据,可能会导致误匹配。
解决方案
为了确保返回的是当前用户的关注信息,可以在查询时增加更多的验证条件。例如:
router.get('/index', async (req, res) => {
try {
const user = await User.findById(req.user.id);
const followList = await FollowList.findOne({
userId: user._id,
username: user.username // 增加额外的验证条件
});
if (!followList) {
return res.status(404).send('Follow list not found');
}
res.render('index', {
username: user.username,
follows: followList.follows
});
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
});
通过增加额外的验证条件,我们可以更准确地获取当前用户的关注信息,从而避免显示错误的信息。
1 回复
根据你的描述和代码示例,问题确实可能出现在 FollowList.findOne()
查询中。目前的查询只基于 userId
来查找关注列表,但没有确保查询结果确实是当前用户的关注信息。为了确保查询结果的准确性,可以增加更多的验证条件来过滤结果。以下是改进后的解决方案:
改进后的解决方案
在查询 FollowList
时,增加额外的验证条件来确保返回的是当前用户的关注信息。可以通过确保 username
一致来增强查询条件。
router.get('/index', async (req, res) => {
try {
const user = await User.findById(req.user.id);
// 确保查询结果是当前用户的关注信息
const followList = await FollowList.findOne({
userId: user._id,
username: user.username
});
if (!followList) {
return res.status(404).send('Follow list not found');
}
res.render('index', {
username: user.username,
follows: followList.follows
});
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
});
解释
- 验证用户身份:首先通过
User.findById(req.user.id)
获取当前登录用户的详细信息。 - 增强查询条件:在
FollowList.findOne()
中增加username
的验证条件,确保返回的关注列表确实是当前用户的。 - 处理未找到的情况:如果查询不到关注列表,则返回 404 错误。
- 渲染页面:将当前用户的用户名和关注信息传递给前端进行渲染。
通过这种方式,可以更准确地获取当前用户的关注信息,避免显示错误的信息。