无法使用 mongoose 查询在 mongoose 查询中获取所需数据

问题描述 投票:0回答:1

这是我下面的代码

 let startDateTimeStr = start_date + "T00:00:00.0000000"; // Making sure to match the number of zeros in the format
      let endDateTimeStr = end_date + "T00:00:00.0000000";
      matchCase.push({
        "start.dateTime": {
          $gte: startDateTimeStr,
        },
        "end.dateTime": {
          $lte: endDateTimeStr,
        },
      });

我需要从这里的其他集合的数据中获取数据。我想要的是,从我的字段中我想选择状态被拒绝的电子邮件 ID。约会集合中的架构如下所示

与会者拥有一系列文档,其中的状态有响应字段,电子邮件地址字段中有地址。

地址包含电子邮件地址。如果被拒绝,请根据回复进行选择。

然后在用户集合中查找匹配的电子邮件地址,并向我返回 user_serial_id,但它什么也没返回。这是我的完整代码的样子

matchCase.push({
  "start.dateTime": {
    $gte: startDateTimeStr,
  },
  "end.dateTime": {
    $lte: endDateTimeStr,
  },
});

matchCase.push({
  "attendees.status.response": { $ne: "declined" },
});

let addFieldsQuery = {
  $addFields: {
    nonDeclinedEmails: {
      $map: {
        input: {
          $filter: {
            input: "$attendees",
            as: "attendee",
            cond: { $ne: ["$$attendee.status.response", "declined"] }
          }
        },
        as: "nonDeclined",
        in: "$$nonDeclined.email"
      }
    }
  }
};

let lookupQuery = {
  $lookup: {
    from: "users",
    localField: "nonDeclinedEmails",
    foreignField: "email",
    as: "nonDeclinedUsers"
  }
};
let projectQuery = {
  $project: {
    user_id: 1,
    description: 1,
    title: "$subject",
    start: "$start.dateTime",
    end: "$end.dateTime",
    type: "appointment",
    resource: "$nonDeclinedUsers.user_serial_id", // populated from lookup
    recurrence: "$recurrence",
    editable: { $toBool: 0 }
  }
};


let aggregatQuery = [];

if (matchCase.length > 0) {
  aggregatQuery.push({
    $match: {
      $and: matchCase
    }
  });
}

aggregatQuery.push(addFieldsQuery);  // add fields for non-declined emails
aggregatQuery.push(lookupQuery);  // perform lookup to get autotask_id

if (Object.keys(projectQuery).length > 0) {
  aggregatQuery.push(projectQuery);
}

console.log(`User id is ${userId}`);

return aggregatQuery;

然后 我执行这段代码

let appointmentsQry = await AppointmentsQuery(req, res);
    
    appointments = await appointmentsModel.aggregate(appointmentsQry).exec();
mongodb mongoose aggregation-framework
1个回答
0
投票

在 $lookup 阶段,本地字段是

nonDeclinedEmails
,它是一个数组,外部字段是
email

这只会匹配用户集合中电子邮件字段完全包含(包括相同顺序)nonDeclinedEmails 列表的文档。

您可能需要先 $unwind nonDeclinedEmails 列表。

© www.soinside.com 2019 - 2024. All rights reserved.