[英]How can i switch TTL index on and off using mongoose?
我想在我的應用程序上創建一個用戶帳戶,如果該用戶尚未確認其帳戶,請在經過一定時間后將該用戶刪除,如果該用戶已確認其帳戶,則將TTL關閉。
這是我的架構:
const mongoose = require('mongoose') const Schema = mongoose.Schema const UserSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true } , isConfirmed: { type: Boolean }, code: { type: String }, createdAt: { type: Date, expires: 3600, default: Date.now } }) module.exports = User = mongoose.model('users', UserSchema)
由於您已經在createdAt
字段上添加了TTL index
,因此您可以通過在成功帳戶確認后刪除createdAt
字段來輕松地將其關閉。
如果文檔具有createdAt
值且早於指定時間,則將其刪除。 但是,如果您在帳戶確認時刪除該字段,則不會刪除該字段。 因此,您需要刪除帳戶確認中的createdAt
字段。
如果要保留createdAt
字段,則可以在一些臨時字段(例如expireAfter
上添加TTL index
,並在帳戶確認時將其刪除。
expireAfter: {
type: Date,
expires: 3600,
default: Date.now
}
帳戶確認后。
User.findOneAndUpdate({_id : user_id},{$unset : {expireAfter:1}})
來自官方文檔:
當文檔的createdAt值大於expireAfterSeconds中指定的秒數(在您的情況下
expires
)時,MongoDB將自動從集合中刪除文檔。
有關更多信息,請閱讀MongoDB TTL索引文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.