Mongodb 如何在mongoose中使子文档在特定日期过期?
我对mongoose中的虚拟教室有以下模式:Mongodb 如何在mongoose中使子文档在特定日期过期?,mongodb,mongoose,mongoose-schema,ttl,subdocument,Mongodb,Mongoose,Mongoose Schema,Ttl,Subdocument,我对mongoose中的虚拟教室有以下模式: var classroomSchema = mongoose.Schema({ studentIds: [mongoose.Schema.Types.ObjectId], teacherIds: [mongoose.Schema.Types.ObjectId], teacherNames: [String], createdAt: { type: Date, default: Date.
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,**
}],
});
我希望每节课在结束日期过后从教室里结束。如何在mongoose中的子文档中使用ttl?不能使用ttl删除文档的一部分。我可以想出另外两个解决方案:
课程
到自己的集合中,并将教室id
放在其中作为教室的参考。这样,您就可以使用ttl单独删除课程
课程
阵列中删除
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
运算符,如示例所示
方法2唯一的缺点是,根据您选择的cronjob时间间隔,课程可以在过期后多持续几分钟