【问题标题】:How to check if a String matches elements of an Array with Mongoose如何检查字符串是否与 Mongoose 的数组元素匹配
【发布时间】:2020-02-06 21:21:20
【问题描述】:

我正在尝试对包含一组流派作为字符串的电影数据库进行查询。格式为genres = "Drama,Action,War。我想要做的是对这个字符串进行查询,检查流派字符串是否包含我数组中的元素之一。

如果我有一部类型字段为"Drama, Action" 的电影和一部带有"Drama, Comedy" 的电影,并且我使用数组["Action","Comedy"] 进行搜索,我希望返回这两部电影。如果这是不可能的,如果流派字段也是一个数组,是否有可能?

【问题讨论】:

    标签: javascript arrays string mongodb mongoose


    【解决方案1】:

    Mongoose 允许您在查询中使用正则表达式,因此您可以尝试以下操作:

    const getMovies = async (genreArray) => {
        const arrayToRegex = genreArray.join('|')
        const results = await Movies.find(
            { "genres": { "$regex": arrayToRegex, "$options": "i" } } 
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2019-10-22
      • 1970-01-01
      • 2010-12-19
      相关资源
      最近更新 更多