【问题标题】:How do you search an array in MongoDB with mongoose如何使用 mongoose 在 MongoDB 中搜索数组
【发布时间】:2022-07-22 00:21:02
【问题描述】:

我目前正在尝试查找字符串数组是否包含某个字符串。到目前为止,我所拥有的是:

Following.find({ username: username }, { following: { $in: [profileUsername] } }).exec((err, result) => {
    if (err) {
        console.log(err);
        res.json(err);
    } else {
        res.json(result);
    }
});

但是,它说 $in 需要两个参数。有没有更好的方法来检查数组是否包含字符串?谢谢

【问题讨论】:

    标签: node.js reactjs mongodb express mongoose


    【解决方案1】:

    $in 没有收到 2 个参数,您只是有语法错误,find 收到的第二个对象是查询选项,而不是查询。你想像这样重写你的查询:

    Following.find({ username: username, following: { $in: [profileUsername] } }).exec((err, result) => {
        if (err) {
            console.log(err);
            res.json(err);
        } else {
            res.json(result);
        }
    });
    

    【讨论】:

      【解决方案2】:

      您不需要使用 $in 查询过滤器,因为这是为了匹配项目列表中的项目,您只需执行普通相等即可

      Following.find({ username: username, following: profileUsername } })
      

      查看 mongo 游乐场示例:https://mongoplayground.net/p/cPF484_xqW5

      【讨论】:

        猜你喜欢
        • 2017-05-14
        • 1970-01-01
        • 2020-07-15
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 2020-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多