2017-12-18 265 views
0

我有以下模式:貓鼬到期

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

我想從創建120秒後自動刪除的消息。但上面的刪除是整個文件,而不僅僅是來自msgboard的subdoc。 我一直在使用cron並運行一個函數,但代碼看起來太凌亂了。有沒有內在的方法?

回答

1

我認爲你應該試試這個,它的工作。 我已經創建了兩個模式針對此問題

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); 

主測試模式:在其中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); 

作爲msgboard是從單獨的測試,這隻會在120s後從Test中刪除msgboard subdocumet,而不是整個測試文檔。

+0

感謝這工作! –