node.js - 30日後にMongoDBのドキュメントを自動削除
私はReact、Express.js、Mongo DBでカレンダーアプリを作っています。このカレンダーは月表示で週ごとのイベントを表示し、これらのイベントを30日後に自動的に削除したいです
私の schema.ts:
import { Calendar } from "../types";
const calendarSchema = new mongoose.Schema<Calendar>(
{
startDate: {
type: String,
required: true,
},
endDate: {
type: String,
required: true,
},
rRule: {
type: String,
},
title: {
type: String,
required: true,
},
notes: {
type: String,
// required: true,
},
type: {
type: String,
required: true,
},
expireAt: {
type: Number,
},
},
{
timestamps: true,
}
);
calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 70 });
export default mongoose.model<Calendar>("Calendar", calendarSchema);そして、フロントエンドで次のように「expireAt」フィールドを作成しています:
const payload = await createAppointment({
...appointment,
expireAt: new Date().getTime() + 80,
});今これは40~50秒でドキュメントを削除します。私の質問は、これを30日か31日にするにはどうすればよいでしょうか?事前にありがとうございます。
回答 #1
expireAtをnumberではなくDateに変更してください
そして、インデックスを作成する際には、expireAfterSeconds に 0 を割り当てます
calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });
これで、各カレンダーが有効期限を迎える正確な日付を、年間単位から秒単位まで設定できるようになりました
詳細については、MongoDBのドキュメントを確認してください
回答 #2
問題は、有効期限を70秒後に設定したことです:
calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 70 });
expireAfterSeconds の 70 の代わりに、希望する値を入力してください。例えば 7 日の場合:
60 * 60 * 24 * 7 = 604800
