javascript - mongo中是否有一个函数来查找数组中是否存在元素?
问题描述
我正在尝试编写一个查询,以使数组中不存在特定的字符串。我的架构是:
_id: {
type: String,
required: true
},
...
meta: {
user_likes: {
type: [String],
},
user_dislikes: {
type: [String],
},
user_liked_by: {
type: [String],
},
user_matches: {
type: [String],
},
...
},
meta
其他文档的key中的对象中的数组内容_id
,类型为String
.
现在我有一个 API 端点来处理这个查询,它是这样的:
router.post('/fetchUsersForClient', async function (req, res) {
/* Body
{
"client_id" : String
}
*/
try {
var client_id = req.body.client_id;
const users = await SampleUser.find(); //query here
res.json(users);
}
} catch (error) {
res.send({ message: error });
}
});
我想编写一个查询,使得该变量client_id
不存在于meta
对象的任何数组中并且client_id
不等于_id
任何文档。
编辑:我尝试使用此查询来获取我的结果,但我不知道如何"1"
在查询中替换。
{
"_id" : {
$ne : "1"
},
$and : [
{
"meta.user_likes" : {
$not : /.*1.*/i
}
},
{
"meta.user_dislikes" : {
$not : /.*1.*/i
}
},
{
"meta.user_matches" : {
$not : /.*1.*/i
}
}
]
}
解决方案
我通过修改给出的代码找到了这个问题的答案。在这里,我使用了一个单独的常量来初始化一个正则表达式模式。这是我的方法:
router.post('/fetchUsersForClient', async function (req, res) {
/* Body
{
"client_id" : String
}
*/
try {
var client_id = req.body.client_id;
var expr = '.*var.*'
expr = expr.replace("var", client_id);
const chkExp = new RegExp(expr);
const users = await User.find(
{
"_id": {
$ne: client_id
},
$and: [
{
"meta.user_likes": {
$not: chkExp
}
},
{
"meta.user_liked_by": {
$not: chkExp
}
},
{
"meta.user_dislikes": {
$not: chkExp
}
},
{
"meta.user_matches": {
$not: chkExp
}
}
]
}
);
res.json(users);
} catch (error) {
console.log(error);
res.send({ message: error });
}
});
推荐阅读
- c# - 带有 MongoDB.Driver 的 Asp.Net Core Web API
- unity3d - Unity OpenXR 从 VR 控制器读取触发器和手柄数据
- amazon-web-services - AWS:将日志从 Amazon CloudWatch 导出到 Amazon Redshift
- debugging - 如何跟踪堆栈以消除 MathCAD 中的错误?
- python - Pyinstaller 中的多个隐藏导入
- python - 如何合并熊猫数据框的行
- leaflet - 传单标记未正确检测触摸位置
- python - 在python中通过子字符串匹配两个数据帧
- python - 如何在 Python Tensorflow-Keras 中腌制弱引用?
- java - ASM ClassReader 无法解析类文件 [class java.lang.Object],可能是由于尚不支持新的 Java 类文件版本