简体   繁体   中英

Mongoose, Remove expired references

I have two collections, guilds and logentries, the reference to logentries are saved as an array in 'guild.mod_log.entries'. The document expires successfully but the reference in 'mod_log.entries' doesn't get removed.

So I'm just wondering how would I remove those expired references.

Here are the schema parts

 // guilds.js module.exports = new mongoose.Schema({ _id: {type: String, required: true}, members: [require('./guildMember')], mod_log: require('./guildModLog'), default_role: String }); // guildModLog.js module.exports = { enabled: {type: Boolean, default: false}, channel_id: {type: String}, entries: [{type: mongoose.Schema.Types.ObjectId, ref: require('./modLogEntry')}] }; // modLogEntry.js module.exports = new Schema({ action: {type: String, required: true, enum: ['Ban', 'Unban', 'Kick', 'Warn']}, timestamp: {type: Date, required: true, expires: '5s'}, user: {type: String, required: true}, staff: {type: String, required: true}, reason: {type: String, required: true, minlength: 5, maxlength: 100}, }); 

You could restructure the schema so that the link between guild and entry is a foreign key.

// guildModLog.js
module.exports = {
    enabled: {type: Boolean, default: false},
    channel_id: {type: String}
};

// modLogEntry.js
module.exports = new Schema({
    _guild_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Guilds',
      index: true
    }
    action: {type: String, required: true, enum: ['Ban', 'Unban', 'Kick', 'Warn']},
    timestamp: {type: Date, required: true, expires: '5s'},
    user: {type: String, required: true},
    staff: {type: String, required: true},
    reason: {type: String, required: true, minlength: 5, maxlength: 100},
});

Doing this means you can't use .populate() to get at the mod log entries for a guild but it keeps all the data to be expired in the one collection. Writing a simple .find() is easier than trying to expire data in a non TTL collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM