'Check DB Array for Duplicate Key on Form Submit
This is a MERN stack app. I have a "WeekMealPlans" collection and "Days" collection, where each Day must have a WeekMealPlan and a "DayOfWeek", as in "Friday," and it has a name that combines WeekMealPlan and DayOfWeek like "Week 1 - Monday."
I want to prevent a duplicate combo of WeekMealPlan + DayOfWeek, so in my Day Mongoose Model, "name" has attribute "unique."
In React, I set a Days array in State with an Axios call, so all Days are available to check for duplicates on form submit.
On form submit, I just want to take the generated "Day Name," check it against the Days array for a duplicate, and alert the user if a dup is found.
I've tried an If Statement inside a For Loop, as well as Array.find. Both do not seem to work per the below. Do If Statements, For Loops and Array.find, as well as Undefined variable not work the same in React as in Vanilla JS?!
//Here's the Days Array:
[
{
_id: "609f3e444ee536749c75c72b",
dayOfWeek: "Monday",
weekMealPlan: {
_id: "609f3e444ee536749c75c72a",
name: "JD Hypertrophy Week 1",
GRFUser: "609f3e444ee536749c75c729",
createdAt: "2021-05-15T03:21:40.285Z",
updatedAt: "2021-05-15T03:21:40.285Z",
__v: 0,
},
__v: 0,
},
{
_id: "610dbb89bebaea6004ce9f53",
dayOfWeek: "Sunday",
weekMealPlan: {
_id: "609f3e444ee536749c75c72a",
name: "JD Hypertrophy Week 1",
GRFUser: "609f3e444ee536749c75c729",
createdAt: "2021-05-15T03:21:40.285Z",
updatedAt: "2021-05-15T03:21:40.285Z",
__v: 0,
},
createdAt: "2021-08-06T22:45:29.826Z",
updatedAt: "2021-08-06T22:45:29.826Z",
__v: 0,
},
{
_id: "622ac86263a8575ecb8c0f5e",
name: "JP Nash's WMP - Friday",
dayOfWeek: "Friday",
weekMealPlan: {
_id: "62283f3d398c00aee52b7e99",
name: "JP Nash's WMP",
GRFUser: "62283f21398c00aee52b7e93",
createdAt: "2022-03-09T05:46:37.756Z",
updatedAt: "2022-03-09T05:46:37.756Z",
__v: 0,
},
createdAt: "2022-03-11T03:56:18.136Z",
updatedAt: "2022-03-11T03:56:18.136Z",
__v: 0,
},
];
//For Loop method:
let isDayDup = false;
const daysArray = this.state.days;
const dayName = this.state.name;
let i = 0;
{
for (i = 0; i < daysArray.length; i++) {
if (daysArray[i].name == dayName) {
isDayDup = true;
}
}
}
console.log(isDayDup);
//No matter whether the passed Day Name is or is not a duplicate, the result is "false"!
//Array.find method:
const daysArray = this.state.days;
const dayName = this.state.name;
function findDayDup(thisDay) {
return thisDay.name == dayName;
}
const dupDay = daysArray.find(findDayDup);
if (dupDay == undefined) {
console.log("Duplicate Day Name!");
} else {
console.log("Day is OK!");
}
//No matter whether the passed Day Name is or is not a duplicate, the result is "Duplicate Day Name"!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
