如何执行多个查询以仅返回我的数据的一部分

马特·查诺克

我在 MEAN 应用程序中返回特定数据时遇到问题。我试图只返回我的猫鼬模式(发票)的特定部分。我目前正在通过它的 ID 获取特定的发票,然后我试图检查发票是否在嵌套数组中包含“invoiceType”这等于一个特定的参数。

我试过使用 find({'_id': userId}, {'services.serviceType': 'one'}),但它返回两种服务类型,无论是 serviceType 是一还是二。

// 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");
  });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何仅解析JSON的一部分?

如何仅显示图像的一部分

如何仅修改URL中“查询”的一部分?

我如何使用sql在一行中仅返回一部分值

如何仅更改状态的一部分?

如何仅分析图像的一部分?

如何使我的代码的一部分可供多个活动访问

如何从api的一部分接收数据到另一部分

如何将下一个查询转换为Power Query,我只能执行第一部分

如何只返回一部分数据?

TypeScript:仅返回接口的一部分

如何仅选择Tensorflow数据集的一部分并更改尺寸

如何在仅连接外部查询集的一部分的Django中创建ForeignKey?

为什么我的&&条件的第二部分有效(仅当第一部分为true时才执行)

如何仅编码URL的一部分

如何在PHP中仅回显数据的一部分?

根据屏幕大小仅执行jQuery的一部分

如何仅将我的精灵图像的一部分重复作为div的背景

Java不返回整个HTML字符串,仅返回一部分

我如何迭代从Mongodb返回的arrayList作为结果的一部分?

仅随机化一部分查询结果

如何返回对递归数据结构的一部分的引用?

如何仅渲染Sprite的一部分

如何基于查询结果(使用Eloquent或原始SQL)执行/返回查询的一部分?

我如何清除状态的一部分

如何仅加粗段落的一部分?

如何仅验证我通过获取请求获得的值的一部分?

如何仅打印 JSON 对象数据的一部分?

如何仅转置数据框的一部分或交换行和列?