我想在文档创建 3 分钟后将其删除。定义文档创建时刻的字段是 expiresAt。这是我迄今为止的设置。该文档在 3 分钟后并未按其应有的方式删除。
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const PostsAmountsTimeframesSchema = new Schema({
posts_amounts_timeframe: Number,
expireAt: {
type: Date,
default: new Date()
},
userid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
})
PostsAmountsTimeframesSchema.index( { expireAt: 1 }, { expireAfterSeconds: 180 } )
const PostsAmountsTimeframes = mongoose.model('PostsAmountsTimeframes', PostsAmountsTimeframesSchema)
module.exports = PostsAmountsTimeframes
也尝试过
expireAt: {
type: Date,
default: new Date(),
expires: 180,
}
相同的结果。
PS:这是在服务器上创建文档的方式:
PostsAmountsTimeframes.create({
userid: req.session.userId,
posts_amounts_timeframe: req.session.posts_amounts_timeframe,
// expireAt: d
}, (error, postsamountstimeframes) => {
console.log(error)
})
最佳答案
解决方案
- 删除整个集合
- 删除集合中的所有索引
- 将代码更改为:
const mongoose = require('mongoose')
//Create empty Schema object?
const Schema = mongoose.Schema
//Models are defined through the Schema interface
//Models define collections
const PostsAmountsTimeframesSchema = new Schema({
posts_amounts_timeframe: Number,
expireAt: {
type: Date,
},
userid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
})
PostsAmountsTimeframesSchema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });
//Access the database my_database via mongoose.model.
//The first argument: The name of the collection the model is for.
//Apply the model to the collection?
const PostsAmountsTimeframes = mongoose.model('PostsAmountsTimeframes', PostsAmountsTimeframesSchema)
//Export User variable to other files
module.exports = PostsAmountsTimeframes
使用它来创建条目。我在当前日期后 3 分钟使收集过期。
var d = new Date()
d.setMinutes(d.getMinutes()+3);
var r = new Date(d)
PostsAmountsTimeframes.create({
userid: req.session.userId,
posts_amounts_timeframe: req.session.posts_amounts_timeframe,
expireAt: r
}, (error, postsamountstimeframes) => {
console.log(error)
})
- 关闭 mongosh
- 关闭 Mongo Compass
- 重建项目
- 重新运行项目
- 创建一个条目,然后砰!创建后它会自动删除自己 一个条目。
应该有一种方法可以对 TTL 过期做同样的事情。目前正在研究该方法!
关于node.js - Mongoose Schema 设置过期字段来删除文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71273672/