【问题标题】:How to filter this array based on an array of object within an array of object如何根据对象数组中的对象数组过滤此数组
【发布时间】:2021-05-18 10:05:01
【问题描述】:

我已经被这个问题困住了几个小时了。假设我的潜在客户对象有一个matched_listings 字段并且匹配列表字段有一个listing.contact_details 对象数组,里面有一个电子邮件字段,我需要根据对象的listing_contact_details 数组过滤我的潜在客户数据,基本上返回与电子邮件匹配的所有潜在客户在matched_listings 的listing_contact_details 和我从req.query 获得的电子邮件变量中。我尝试使用集合、过滤器、映射、包含方法来实现,但我似乎无法理解。希望得到一些帮助:)

const getLeads = async (req, res, next) => {
  const email = req.query.email;

  let leads;
  try {
    leads = await Lead.find().populate({
      path: "matched_listings",
      match: { "listing_contact_details.email": email },
    });
  } catch (err) {
    const error = new HttpError("Something went wrong", 500);
    return next(error);
  }

  let matchedLeads;
  //filter logic
  res.json({ response: 'success'});
}; 

//Sample data set:

leads = [
  {
    matched_listings: [
      {
        listingName: "sample name",
        listing_contact_details: [
          {
            email: "email-sample@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },

      {
        listingName: "sample name2",
        listing_contact_details: [
          {
            email: "email-sample@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },
    ],

    leadName: "sample name",
    leadField: "sample field",
  },

  {
    matched_listings: [
      {
        listingName: "sample name",
        listing_contact_details: [
          {
            email: "sample-2@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },

      {
        listingName: "sample name2",
        listing_contact_details: [
          {
            email: "sample-2@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },
    ],

    leadName: "sample name 2",
    leadField: "sample field 2",
  },
];

【问题讨论】:

  • 请添加您拥有的数据示例以及您想要获得的数据
  • 嗨,我已经编辑了问题并在下面附加了一个示例数据集:) 假设我的 req.query = email-sample@gmail.com。我想返回所有在 match_listings 数组中有 email-sample@gmail.com 的线索。

标签: javascript node.js arrays mongoose nodes


【解决方案1】:

如果您想根据单个电子邮件进行过滤,您可以试试这个:

leads = await Lead.find({
"matched_listings.listing_contact_details.email": email
});

【讨论】:

  • 嗨!对不起,但它没有用。它为我返回了一个空数组
  • 可以告诉我什么是 Lead 变量定义为??
  • 你好! ,我已经编辑并附加了上面的线索样本数据集:)
  • await Lead.find({}) 的输出是什么
  • 它返回我在数据库中的所有潜在客户
猜你喜欢
  • 2020-12-14
  • 2021-03-21
  • 2017-05-25
  • 2020-12-03
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 2018-12-25
相关资源
最近更新 更多