gpt4 book ai didi

node.js - 查询数组时 MongoDB 数据匹配和获取问题

转载 作者:太空宇宙 更新时间:2023-11-03 23:11:42 25 4
gpt4 key购买 nike

我想从 MongoDB 获取数据。因为我是 Node.Js 和 MongoDB 的新手。我无法获取数据。

我将主要类别和次要类别传递给一个 API,我希望将主要类别和次要类别与数组字段“category”进行匹配,该数组字段“类别”具有两个索引 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);
});

示例文档:

Database structure screenshot

所以我想输入类似 ['Health','women'] 的内容并获取类别数组中所有这些元素都存在的文档,类似于数组元素的正则表达式搜索。

有人可以帮我从数据库中获取数据吗?

最佳答案

如果您必须使用输入作为 ['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
]
}
}
]
})

关于node.js - 查询数组时 MongoDB 数据匹配和获取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60407819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com