javascript - 检查来自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)
}
}
})
解决方案
我认为问题可能来自这一行: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”文档。)
推荐阅读
- powerbi - 在 Power BI Desktop 中使用单列创建指示器颜色/灯光
- angular - 如何读取路由参数并导航到详细信息页面
- android - 在 Android Studio 中激活/停用两个布局的最佳方法?
- azure-web-app-service - 如何使用 dotnet core 3.1 LTS 创建 Windows 应用服务?
- prolog - 在Prolog中找到平方不大于N的最大整数
- python - 如何减少内存使用这个程序递归
- python - 在 python3.7 虚拟环境中安装 pysftp 时出错
- python - 你将如何为这个贪婪算法 qns 编写代码,我们必须选择玩家的路线,但路线不能重复?
- azure - 构建策略失败时的电子邮件发送选项
- reactjs - react 15中根据复选框状态添加或删除数据