首页 > 解决方案 > 检查来自firebase firestore的数据中的值

问题描述

当我运行我的 func 并获取三个值(标题、id、日期)时,我需要检查标题是否已经在我的数组(nameArr)中对我的数据库有影响

但它不起作用,数据最终会在我的数据库中出现两次或三次

我的代码:

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)
            }

        }

    })

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


我认为问题可能来自这一行:if (nameArr.forEach(x => x.title == title))

“if”语句没有评估x.title == title为条件,我认为这是你想要的。

要解决此问题,您可以将 if 语句嵌套在 forEach 循环中并添加一个布尔变量来确定是否应将标题添加到数据库中。

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
}

编辑添加:您还可以替换.forEach现有.some代码的其余部分并使其保持不变。(参见“.some”文档。)


推荐阅读