【问题标题】:Making Mongoose Aggregate Dynamic/Autonomous使 Mongoose 聚合动态/自治
【发布时间】:2018-05-10 15:45:42
【问题描述】:

我有一个应用程序,用户可以在其中启动项目。一个用户可以有多个项目,每个项目都有一个状态,还包含项目所有者的电子邮件。

项目架构:

const projectSchema = new mongoose.Schema({

 url: {type: String},
 status: {type: String, default: 'incomplete' ,set: toLower},
 sector: {type: String, set: toLower},
 owner: {type: String, set: toLower}, //this contains the owners email
 title: {type: String, set: toLower},

 dateCreated: {type: Date, default: Date.now},

});

我正在尝试向项目状态为“不完整”的用户发送电子邮件,而不是为每个用户发送他们拥有的每个项目的单独电子邮件我希望能够发送一封电子邮件他们的不完整项目列表。

我做了什么:

Project.aggregate([{"$match": {"status": "incomplete", "owner": "jon.smith@email.com"}}], function(err, data) {});

以上内容将jon.smith@email.com 的所有incomplete 项目返回给我。但问题是我必须向用户提供电子邮件。

请注意:此功能不会响应前端用户的操作而运行,而是由服务器在特定时间和日期(Cron Job)运行。

如何使owner 字段自动填充变得更加动态?我可以获得所有项目用户的列表,但是如何使用电子邮件地址填充aggregate 函数?也许forOf loops

仅供参考 - 用户架构:

const userSchema =  new mongoose.Schema({

 email: String,
 password: String,
 fullName: String,
 usersProjects: [] // this contains the _id's of Project document created by the user

});

任何建议将不胜感激。如果您认为我的方法不好,请告诉我如何改进。 (我就是这样学习的)

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    你可以这样做:

    Project.aggregate([
     {"$match": {"status": "incomplete"},
     {"$group":{_id:{"$owner", projects:{$push: "$title"}}}}
    ], function(err, data) {});
    

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 2021-07-21
      • 1970-01-01
      • 2014-08-09
      • 2018-01-30
      • 1970-01-01
      • 2017-10-29
      • 2013-02-24
      • 2018-08-01
      相关资源
      最近更新 更多