英文:
Mongoose document delete automatically after one month
问题
我只想在客户用户删除特定文档后保留一个月,所以我决定进行假删除并在浏览器中显示数据。
我的架构如下:
const product = new mongoose.Schema({
// ...
trash: { type: Boolean, default: false }
});
我只会在浏览器中显示 trash: false 的项目。一旦用户尝试删除,那么 "trash" 键将更改为 trash: true。
我想在浏览器的"垃圾"标签下显示这些已删除的(trash: true)项目,并且我希望从数据库中在一个月后自动删除这些已垃圾的项目。
解决方案:
我知道可以通过在架构中添加 createdAt: { type: Date, expires: '1month', default: Date.now }
来解决,但是这个选项会在创建日期一个月后删除每个项目,我想要的是在 trash: false 变为 trash: true 一个月后删除。
英文:
I just want to keep for one month after client-user will delete document particular document
so I decided to do fake delete and data showing in browser
my schema
const product = new mongoose.Schema({
---
trash : { type: Boolean, default: false }
});
and I will show trash: false item only in browser
,Once user tried to delete then trash key will change to trash : true
I want to show these deleted ( trash : true) items under trash tab in browser and I want to automatically delete these trashed item after one month from DB
Solution
I know there is a solution by adding createdAt: { type: Date, expires: '1month', default: Date.now } in schema
but this option works every item after one month from created date , I want to delete after one month from the change of trash : false to trash : true
答案1
得分: 1
只需创建一个名为 trashedAt
的 date
类型新变量,然后以此为键创建 TTL 索引,如下所示:
db.products.createIndex({ "trashedAt": 1 }, { expireAfterSeconds: 30 * 24 * 60 * 60 })
30(天)* 24(小时)* 60(分钟)* 60(秒)= 1 个月
然后,在更新时也要提及 trashedAt: new Date()
。
db.products.updateOne(
{
"someParameter": "someValue"
},
{
$set:
{
"trash": true,
"trashedAt": new Date()
}
}
)
或者完全从文档中移除 trash
,并使用 trashedAt
的存在来在“回收站”选项卡中显示帖子,如下所示:
db.products.find(
{
"trashedAt":
{
$exists: true
}
})
TTL 需要使用日期或时间戳,因此在创建 trashedAt: date
之前无法执行此操作。
如果将 createdAt
添加为 ttl 索引,它将在创建后一个月内删除文档。
英文:
Just create a new variable like trashedAt
of type date
, and then create TTL index with that as the key, as follows:
db.products.createIndex({ "trashedAt": 1 }, { expireAfterSeconds: 30 * 24 * 60 * 60 })
30 (days) * 24 (hours) * 60 (minutes) * 60 (seconds) = 1 month
Then, while updating also mention trashedAt: new Date()
.
db.products.updateOne(
{
"someParameter": "someValue"
},
{
$set:
{
"trash": true,
"trashedAt": new Date()
}
}
)
or just remove trash
completely from the document and use existence of trashedAt
to show posts in Trash Tab, as follows:
db.products.find(
{
"trashedAt":
{
$exists: true
}
})
TTL needs a date or timestamp to be used, so you can't do so without creating trashedAt: date
.
And if you add createdAt
as the ttl index it will just delete the document one month after it was created.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论