node.js - 查询数组时出现 MongoDB 数据匹配和获取问题
问题描述
我想从 MongoDB 中获取数据。因为我是 Node.Js 和 MongoDB 的新手。我无法获取数据。
我将主要类别和次要类别传递给一个 API,我想在其中将主要和次要类别与具有两个索引 0 和 1 的数组字段“类别”匹配,在 0 索引中主要类别存在并且在 1 索引中次要类别由 ~ 分隔。
下面是我根据主要类别获取数据的代码,但我想通过匹配数据库中的主要和次要类别来获取数据。
ProductModel
.find({ category : { $all : [req.body.primary] }})
.select('id link brand title description category image images in_stock price sale_price merchant_number part_number GroupID status promotion attributes tags currency updated -_id')
.then((productList) => {
response.status = 200;
response.msg = 'Success';
response.count = productList.length;
response.data = productList
res.json(response);
})
.catch(() => {
response.status = 500;
response.msg = 'connection error';
response.data = [];
res.json(response);
});
样本文件:
所以我想输入类似['Health','women']
& get docs 之类的东西,其中类别数组中的所有这些元素都存在,一种对数组元素的正则表达式搜索。
有人可以帮我从数据库中获取数据吗?
解决方案
如果您必须使用输入进行查询并['Health', 'women']
获取已列出的文档并获取具有以下内容的文档:category : ["Health", "tes~men~women"]
那么您可以尝试以下查询:
询问 :
db.collection.find({
$and: [
{
category: {
$in: [
/\bwomen\b/
]
}
},
{
category: {
$in: [
"Health"
]
}
}
]
})
JS代码:
const secondary = req.body.secondary
const primary = req.body.primary
db.collection.find({
$and: [
{
category: {
$in: [
new RegExp(`\\b${secondary}\\b`, 'i')
]
}
},
{
category: {
$in: [
primary
]
}
}
]
})
推荐阅读
- javascript - 如何在没有控制台的情况下发送推送通知
- python - 将密钥发送到游戏容器 2048
- python - 下面的加速程序
- oracle - 在 select 语句中使用聚合函数
- neo4j - 新4j。匹配节点,但如果有我需要返回边
- powershell - 为什么 Powershell 的 Install-Module 速度如此之慢?
- java - 使用 OkHttp 访问 API 时获得空响应
- javascript - mxGraph 从 XML 加载,但加载后无法插入元素
- android - 推送通知需要打开特定的活动
- sql-server - 即使重新启动,内存使用服务器 DB 也总是增加