首页 > 解决方案 > 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)

     });

标签: node.jsexpressmongoose

解决方案


您需要使用 $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");
  });


推荐阅读