node.js - 按数组中的对象过滤文档
问题描述
我的架构中有一个字符串数组,我试图根据它们的数组是否包含某些字符串来过滤文档。下面是我的架构,其中成分数组是我要过滤的内容:
const foodSchema = mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
ingredients: [
{
type: String,
required: true,
trim: true,
},
],
});
在 nodejs 中,我的快速路由器中有以下内容:
router.get('/food', auth, async (req, res) => {
const match = {};
if (req.query.name) {
match.name = req.query.name;
}
if (req.query.ingredients) {
match.ingredients = req.query.ingredients;
}
try {
const allFood = await Food.find(match);
res.send({
allFood,
});
} catch (error) {
res.status(400).send(error);
}
});
这是发送的示例请求:
{{url}}/food?ingredients=Salmon Meal&ingredients=Deboned Turkey
我希望获得所有食品文件,其中他们的成分数组包含三文鱼粉和去骨火鸡,但我总是得到一个空数组。外壳是正确的。如果我只在查询中使用一种成分,它就可以正常工作。
解决方案
利用$in
if (req.query.ingredients && req.query.ingredients.length > 0) {
match.ingredients = { $in: req.query.ingredients };
}
推荐阅读
- android - Acces a complex json object in Ionic 3 and bind to view
- c# - C# Slotmachine 获胜算法
- php - 在 Woocommerce 中的条件自定义结帐字段上显示现有值
- ios - 错误 ITMS-90715:“最低操作系统太低
- c# - 是否可以观察布尔值直到变化?(C#)
- solr - Solr 在父文档和子文档中搜索和评分
- objective-c - 如何关闭全屏 UIImageView?
- android - 从应用程序 android 打开当前正在进行的呼叫
- mqtt - 如何在 mqtt mosquitto 中发布从订阅经纪人获取的数据?
- c# - 修复链接中的 PDF 可访问性问题(注释缺少替代描述)