Har*_*ash 0 mongoose mongodb node.js mongoose-schema
我有以下架构:
ip: String,
port: Number,
msgboard: [{
date: {
type: Date,
default: Date.now,
expires: 120
},
msg: String
}]
Run Code Online (Sandbox Code Playgroud)
我希望消息在创建 120 秒后自动删除。但上面的删除是整个文档,而不仅仅是 msgboard 中的子文档。我一直在使用 cron 并运行一个函数来做到这一点,但代码看起来太不整洁了。有没有内置的方法?
我认为你应该尝试这个,它的工作原理。我为这个问题创建了两个模式
消息板架构:
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);
Run Code Online (Sandbox Code Playgroud)
主要测试架构:其中存储 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);
Run Code Online (Sandbox Code Playgroud)
由于 msgboard 与 Test 是分开的,因此这只会在 120 秒后从 Test 中删除 msgboard 子文档,而不是整个测试文档。