Reputation: 23
when i'm run my func and get three values (title,id,date) i'm need to check if title already in my array (nameArr )that resive for my DB
but its dont work , the data end up in my DB twice or three time
my code :
const subscribe = async (title, id, date) => {
const movieRef = db.collection("Members")
const snapshot = await movieRef.get()
snapshot.forEach(doc => {
if (doc.data().id == sessionStorage["id"]) {
let nameArr = [...doc.data().subscribe_movie_name]
if (nameArr.forEach(x => x.title == title))
{
console.log("pass")
}
else {
nameArr.push({ title: title, id: id, date: date })
db.collection('Members').doc(doc.id).update(
{
subscribe_movie_name: nameArr
})
setCountSub(countSub + 1)
}
}
})
Upvotes: 0
Views: 92
Reputation: 138
I think the issue might be coming from this line: if (nameArr.forEach(x => x.title == title))
The "if" statement is not evaluating x.title == title
as the condition, which I think is what you want.
To fix this, you can nest the if statement inside the forEach loop and add a boolean variable to determine whether the title should be added to the DB.
let addToDB = true
nameArr.forEach(x => {
if (x.title == title) {
// if title exists in nameArr, set addToDB to 'false'
addToDB = false
}
}
if (addToDB) {
// add data to DB
}
Edit to add: You could also replace .forEach
with .some
and keep the rest of your existing code the same. (See the '.some' docs.)
Upvotes: 1