[英]How to look for strings in array using regex with MongoDB.?
I have several objects like this:我有几个这样的对象:
"status": "published",
"term_id": [
"anime",
"sci-fi",
"etc"
],
"captionCert": "1",
I know that in order to look within a single field, I would create something like this:我知道为了查看单个字段,我会创建如下内容:
if (keyword) {
query.status = { $regex: keyword, $options: 'i' };
}
Where keyword comes from the front end and can be whatever the user types;关键字来自前端,可以是用户输入的任何内容; then I proceed to look into the field status and then I just retrieve it by passing it into my model query:然后我继续查看字段状态,然后通过将其传递给我的 model 查询来检索它:
Video.find(query)
Now hte problem is that I need to know how to exactly do this but inside the term_id array?现在的问题是我需要知道如何在 term_id 数组中准确地做到这一点?
Any idea?任何想法? Thanks.谢谢。
UPDATE: I'm trying to implement it into this function:更新:我正在尝试将它实现到这个 function 中:
exports.searchVideos = asyncHandler(async (req, res, next) => {
const query = {};
const { keyword } = req.query;
if (keyword) {
query.title = { $regex: keyword, $options: 'i' };
} else {
query.text = { $regex: keyword, $options: 'i' };
}
if (keyword) {
query.term_id = { term_id: { $regex: keyword, $options: 'i' } };
};
const video = await Video.find(query).select(
'title text thumbnail video_url term_id'
);
console.log(query);
res.status(200).json({ success: true, data: video });
});
Solution after finding out about $or operator.了解 $or 运算符后的解决方案。 This solved my problems::这解决了我的问题::
exports.searchVideos = asyncHandler(async (req, res, next) => {
let query = {};
const { keyword } = req.query;
query = {
$or: [
{ title: { $regex: keyword, $options: 'i' } },
{ text: { $regex: keyword, $options: 'i' } },
{ term_id: { $regex: keyword, $options: 'i' }}
]
};
const video = await Video.find(query).select(
'title text thumbnail video_url term_id'
);
res.status(200).json({ success: true, data: video });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.