我正在尝试建立一个模型,以便在添加表时,它会有一个到期日期,到期后,表将自行删除。我尝试像这样实现它:
expires: '1m'
并与
expires: 10
我的表格设置如下:
const verifySchema = new mongoose.Schema({
_userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
hash: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: '1m' }
});
问题是,一分钟后什么也没有发生。它不会在数据库中被删除。我做错了什么吗?
如何在一分钟后删除表格?
最佳答案
这是一个使用 mongoose v5.5.9
的工作示例。事实证明,缺少的部分是架构条目 index: { expires: '1m' }
在 createdAt
字段。
const mongoose = require('mongoose')
// $ npm install uuid
const uuid = require('uuid')
const ObjectId = mongoose.Types.ObjectId
// Avoid deprecation warnings
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
// Create the schema.
const verifySchema = new mongoose.Schema({
_userId: {
type: ObjectId,
required: true,
ref: 'User'
},
hash: { type: String, required: true },
createdAt: {
type: Date,
required: true,
default: Date.now,
index: { expires: '1m' }
}
},
{
collection: 'verify'
});
// Connect to mongodb.
mongoose.connect('mongodb://localhost/test').then(() => {
// Create the model
const Verify = mongoose.model('Verify', verifySchema)
// Create a model instance.
const v = new Verify({
_userId: new ObjectId(),
hash: uuid.v4()
})
// Save the model.
v.save().then(() => {
// Close the connection.
mongoose.connection.close()
})
})
您可以使用 MongoDB Compass 检查您的索引,或使用外壳:
> use test
> db.verify.getIndexes()
查找字段值 expireAfterSeconds
这将指示为索引设置的 TTL 时间(以秒为单位)。为了更改 TTL,您需要删除 createdAt
上的索引。 。在 shell 中,命令为 db.verify.dropIndex(<index_name>)
或db.verify.dropIndexes()
删除集合上的所有索引。
用于更新插入文档,例如 findOneAndUpdate ,您需要通过 setDefaultsOnInsert: true
像这样的选项:
// Connect to mongodb.
mongoose.connect('mongodb://localhost/test').then(() => {
// Create the model
const Verify = mongoose.model('Verify', verifySchema)
const _userId = new ObjectId()
const hash = uuid.v4()
const options = { upsert: true, setDefaultsOnInsert: true }
// Upsert the document.
Verify.findOneAndUpdate( { _userId }, { hash }, options).then(() => {
mongoose.connection.close()
})
})
这是必要的,否则createdAt
包含 TTL 索引的字段不会添加到文档中。
关于node.js - Mongo DB文档过期后不会删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211850/