简体   繁体   English

猫鼬到期

[英]Mongoose expiry

I have the below schema: 我有以下架构:

ip: String,
port: Number,
msgboard: [{
   date: {
        type: Date,
        default: Date.now,
        expires: 120
        },
   msg: String
}]

I want the messages to be removed automatically after 120s from creation. 我希望从创建120秒后自动删除邮件。 But the above delete's the whole document and not just that subdoc from msgboard. 但是上述删除的内容是整个文档,而不仅仅是msgboard中的子文档。 I have been doing it using cron and running a function, but the code seems too untidy. 我一直在使用cron并运行一个函数来执行此操作,但是代码似乎过于混乱。 Is there any inbuilt way ? 有内置的方法吗?

I think you should try this, its working. 我认为您应该尝试一下,它会起作用。 I have created two schemas for this problem 我为这个问题创建了两个模式

msgboard schema : msgboard模式:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var msgboardSchema = new Schema({
    date: {
        type: Date,
        default: Date.now,
        expires: 120
        },
    msg: String
});

module.exports = mongoose.model('msgboard', msgboardSchema);

Main Test Schema : In which reference of msgboard is stored 主要测试架构:其中存储了msgboard的引用

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var TestSchema = new Schema({
    ip : { type : String },
    port : { type : String },
    msgboard : [{type : Schema.Types.ObjectId, ref : 'msgboard'}]   
});

module.exports = mongoose.model('Test', TestSchema);

As msgboard is separate from Test, this will only remove msgboard subdocumet from Test after 120s and not whole test document. 由于msgboard与Test分开,因此只会在120秒后从测试中删除msgboard子文档,而不是整个测试文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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