我正在MongoDB中存储聊天应用程序消息。X次之后,我希望他们删除自己。
我在代码的哪里添加来自Docs 的行
{expireAfterSeconds: x }
我创建项目的代码是
try {
MessageModel.create({
username: user.username,
text: msg,
time: moment().format('h:mm a'),
room: user.room
})
} catch (error) {
// do stuff
}
我的模型如下
const MessageSchema = new mongoose.Schema(
{
userName: String,
text: String,
time: String,
room: String
},
{ collection: 'messages' }
)
const messageModel = mongoose.model('MessageSchema', MessageSchema)
我要将代码添加到模型中吗?还是作为create方法的第二个参数?
提前感谢
MongoDB TTL收集功能是通过使用索引来设置的。
- 首先,修改时间字段以将时间戳存储为有效的日期类型。您可以使用
moment().toISOString()
const MessageSchema = new mongoose.Schema(
{
userName: String,
text: String,
time: String,
room: String,
},
{ collection: 'messages' }
)
- 这样设置TTL索引
db.messages.createIndex( { "time": 1 }, { expireAfterSeconds: 3600 } )
有关更多信息,请查看文档