简体   繁体   English

如何使用 mongoose 在 MongoDB 中搜索数组

[英]How do you search an array in MongoDB with mongoose

I am currently trying to find if an array of strings contains a certain string.我目前正在尝试查找字符串数组是否包含某个字符串。 So far, what I have is:到目前为止,我所拥有的是:

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

However, it says that $in expects two arguments.但是,它说 $in 需要两个参数。 Is there any better way to check whether the array contains the string?有没有更好的方法来检查数组是否包含字符串? Thanks谢谢

$in doesn't receive 2 arguments, you just have a syntax error, the second object find receives is query options, not a query. $in没有收到 2 个参数,你只是有一个语法错误,第二个对象find收到的是查询选项,而不是查询。 You want to rewrite your query like so:你想像这样重写你的查询:

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

You don't need to use the $in query filter as this is to match an item within a list of items, you can just do a normal equality您不需要使用$in查询过滤器,因为这是为了匹配项目列表中的项目,您可以执行正常相等

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM