使用nodejs检查存储在mongodb中的数组中特定值的数量

Check amount of certain value in array that is stored in mongodb with nodejs

我有一个问题,因为我正在尝试检查某个值在存储在 MongoDB 中的数组中是否可用超过 1 次。我使用的渲染模板是 EJS,因此数组的循环槽目前正在工作,但现在我试图让它检查项目“绷带”的数量,但我不知道如何才能让它工作。当您尝试删除某个项目时会触发该函数,因此它必须检查您拥有多少该特定项目,然后对其进行处理。 user_items 存储在存储在 MongoDb 的数组中,<% %> + "" 用于 EJS 模板,因为它是一堆字符串,所以必须用 " ".

这是我到目前为止在 EJS 页面上尝试做的事情:

<script>
const user_items = ["<%= user.items%>"]



//Checking if item(s) exist and delete them for the browser.


function  deleteitembandage(user_items){
const count = {}
const result = []

user_items.forEach(user_item => {
    if (count[user_item]) {
       count[user_item] +=1
       
     if ("Bandage" > 1) {
     alert('You have more then 2 Bandages')
}

       return
    }
    count[user_item] = 1
})

for (let prop in count){
    if (count[prop] >=2){
        result.push(prop)
    }
}

console.log(count)
return result;

}

deleteitembandage(user_items)


//Event listener delete button for bandage
document.getElementById('inventorydeletebandage').addEventListener('click', deleteitembandage)


</script>

但是这会给我错误:Uncaught TypeError: user_items.forEach is not a function 在 HTMLButtonElement.deleteitembandage(库存:105)。

这样做的方法是什么?

使用array.filter创建一个仅包含“绷带”项目的数组。然后检查该数组的长度。确保字符串 Bandage 与数组中的内容完全相同(upper/lower 区分大小写)。

const bandageCount = user_items.filter(item => item === "Bandage").length