作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
半新开发人员使用 MERN 堆栈构建项目。
该应用有两种模型,一种用于用户
,一种用于锦标赛
。锦标赛模型有一个名为 participants
的属性,它是一个数组。
我编写了一个 Express 后端路由,以便用户可以注册 Tournaments.participants[]。这看起来像:
router.post('/:id', (req, res) => {
Tournament.findById(req.params.id)
.then(tournament => {
tournament.participants.push(req.body);
return tournament.save();
})
.then(savedTournament => res.json(savedTournament))
.catch(err => res.json(err));
});
但是,用户只需继续单击“注册”,我就会有一堆重复的用户,因此我尝试编写一个条件,如果用户已在 Tournament.participants[] 中,则将禁用“注册”。
我尝试使用 Array.includes(req.body) 在 Express 路由中编写条件,但无法破解它。看起来像
Tournament.findById(req.params.id)
.then(tournament => {
if (tournament.participants.includes(req.body) {
return res.status(400).json({ msg: "This user already signed up for this tournament" });
} else {
tournament.participants.push(req.body);
return tournament.save();
}
})
.then(savedTournament => res.json(savedTournament))
.catch(err => res.json(err));
我也尝试了不同的变体,例如if (tournament.participants.includes(!req.body))
then push(req.body)等
我也尝试过在 participants.includes(user)
的情况下渲染一个不同的按钮,但我相信这应该在后端完成。我愿意接受建议。
谁能帮帮我吗?
最佳答案
一般来说,您不能对对象使用 native 比较运算符,includes
包括:
const foo = { id: 1 };
const bar = [{ id: 1 }];
console.log(bar.includes(foo)); // outputs `false`
您应该使用某种项目id
来检查它是否已经存在:
function isIdIncluded(arr, id) {
return arr.some(x => x.id === id)
}
const foo = { id: 1 };
const bar = [{ id: 1 }];
console.log(isIdIncluded(bar, 1)); // outputs `true`
关于javascript - MERN 堆栈 : How to prevent a User from registering (being added to an array) multiple times?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61232073/
我是一名优秀的程序员,十分优秀!