node.js - How to execute multiple queries to return only a single part of my data
问题描述
I'm having trouble returning a specific piece of data in my MEAN app. I'm trying to return only a specific part of my mongoose schema(Invoice).. I'm currently fetching the specific invoice by it's ID, then I'm trying to check if the invoice contains an "invoiceType" inside a nested array that equals a specific parameter.
I've tried using find({'_id': userId}, {'services.serviceType': 'one'}), but that returns both service types, regardless of being serviceType one or two.
// This is my array.. I'm trying to return the serviceType and serviceDescription if serviceType is equal to 'one'
{
'id': number,
'fistName': string,
'services': [
'serviceType': string
'serviceDescription': string
]
}
// here is my express code where i'm trying to make the call
Invoice.find({'_id': invoice_id},{'services.serviceType': 'one'})
.then(invoice => {
res.json(invoice)
});
解决方案
您需要使用 $elemMatch 搜索内部数组,如下所示:
Invoice.findOne({ '_id': invoice_id }, { 'services': { $elemMatch: { "serviceType": "one" } } })
.then(invoice => {
res.json(invoice)
})
.catch(err => {
console.log(err);
return res.status(500).send("someting went wrong");
});
如果你想从响应中过滤其他 serviceTypes,你可以像这样过滤它们:
Invoice.findOne({ '_id': invoice_id }, { 'services': { $elemMatch: { serviceType: "one" } } })
.then(invoice => {
if (!invoice) {
return res.status(404).send("Not found");
}
let filteredServiceTypes = res.services.filter(s => s.serviceType === "one");
invoice.services = filteredServiceTypes;
return res.json(invoice);
}).catch(err => {
console.log(err);
return res.status(500).send("someting went wrong");
});
推荐阅读
- content-management-system - 如何使用子域和共享内容创建多站点博客
- javascript - 如何在悬停时改变形状粒子的颜色?粒子JS?
- java - 在java中读取整个HTML
- google-sheets - 谷歌表格中带有两个标签的查询功能
- powershell - 在线交换 - 使用 powershell 移动消息
- database - 在颤振中使用 sqflite 保存嵌套模型的有效方法
- reactjs - React Native - 长按并显示额外信息
- javascript - SVG 在 react-natvie 中表现得很奇怪
- javascript - 为在 Nodejs 项目中导入文件定义文件路径或文件夹路径的最佳方法
- ubuntu - 芹菜守护进程启动错误