2017-06-29 91 views
1

我对猫鼬虚拟教室下面的模式:如何使子文件在猫鼬的特定日期到期?

var classroomSchema = mongoose.Schema({ 
    studentIds: [mongoose.Schema.Types.ObjectId], 
    teacherIds: [mongoose.Schema.Types.ObjectId], 
    teacherNames: [String], 
    createdAt: { 
     type: Date, 
     default: Date.now(), 
    }, 
    lessons: [{ 
     name: String, 
     startDate: { 
      type: Date, 
      min: Date.now(), 
     }, 
     endDate: { 
      type: Date, 
      min: Date.now(), 
     }, 
     **expiresAt: endDate,** 
    }], 
}); 

我想每节课从教室theer结束日期过后到期。我如何在猫鼬的子文档中使用TTL?

回答

1

文档的一部分不能用ttl删除。我能想到的其他两个选项作为一种解决方法:

  1. 参考

取出lesson自身的收集,并放置在classroom_id作为参考教室。这样你就可以用ttl单独删除课程。

  • 的cronjob /调度
  • 使用像cron调度运行工作,每隔几分钟/小时在教室教训,找到到期日通过并删除它们来自lesson数组。

    var CronJob = require('cron').CronJob; 
    
    var job = new CronJob({ 
        cronTime: '00 */20 * * * *', //run every 20 minutes 
        onTick: function() { 
         //Find classrooms with lessons which have expiry date smaller than Date.now 
         //Remove those lessons from array and update the classrooms 
        }, 
        start: false, 
        timeZone: 'America/Los_Angeles' 
    }); 
    
    job.start(); 
    

    对于子文档的阵列内搜索expiresAt可以使用$elemMatch操作者,如图this例子。

    方法2唯一的缺点是,根据您选择的cronjob间隔,课程可以持续通过其失效日期几分钟。