gpt4 book ai didi

javascript - MERN 堆栈 : How to prevent a User from registering (being added to an array) multiple times?

转载 作者:行者123 更新时间:2023-12-02 21:05:38 25 4
gpt4 key购买 nike

半新开发人员使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com