简体   繁体   English

如何更新 mongoose 中 createdAt 字段的 expires 属性以避免文档被删除?

[英]How can I update the expires property on createdAt field in mongoose to avoid the document being deleted?

I am trying to add account verification to this app and I have set a user account that has been created but not verified to delete itself after 30 seconds using.我正在尝试向此应用程序添加帐户验证,并且我设置了一个已创建但未验证的用户帐户,以便在使用 30 秒后自行删除。

createdAt: {
  type: Date,
  default: Date.now,
  index: {
    expires: 30,
  },
},

But now I am looking for a way to prevent the document from being deleted after 30 seconds but I haven't found a working solution.但是现在我正在寻找一种方法来防止文档在 30 秒后被删除,但我还没有找到可行的解决方案。

This should do the trick for you:这应该对你有用:

Let's say this is User model.假设这是User模型。

await User.syncIndexes();

The other thing you will need to update in User model is:您需要在User模型中更新的另一件事是:

createdAt: {
  type: Date,
  default: Date.now,
},

Mongoose uses MongoDB TTL indexes to expire documents, see https://docs.mongodb.com/manual/core/index-ttl/ Mongoose 使用 MongoDB TTL 索引使文档过期,参见https://docs.mongodb.com/manual/core/index-ttl/

If the indexed field in a document is not a date or an array that holds a date value(s), the document will not expire.如果文档中的索引字段不是日期或保存日期值的数组,则文档不会过期。

If a document does not contain the indexed field, the document will not expire.如果文档不包含索引字段,则文档不会过期。

So to prevent the document expiring you might unset the field, set it to a non-date value, or set the date into the far future.因此,为了防止文档过期,您可能会取消设置该字段,将其设置为非日期值,或将日期设置为遥远的未来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM