繁体   English   中英

删除从当前日期开始超过 3 个月的所有记录 Mongodb node.js

[英]Delete all records older than 3 months from current date Mongodb node.js

在我的应用程序中,我将用户的活动日志存储在我的数据库 (mongoDB) 中,因为很多日志是在 3 个月内收集的,所以我想删除所有从当前日期开始超过 3 个月的活动日志记录 我的后端使用 Node.js。 我想每天自动运行这个 function 请帮我解决一下这个。

这是日志 model

const logSchema = new mongoose.Schema(
  {
    activityType: {
      type: String,
      require: true,
      enum: {
        values: [
          'create',
          'update',
          'delete',
          'login',
          'logout',
          'passwordReset',
        ],
        message: 'Wrong activity type!',
      },
    },
    activitySubject: {
      type: Object,
      require: true,
    },
    activityPerformedUserId: {
      type: String,
      require: true,
    },
  },
  { timestamps: true }
);

const Log = mongoose.model('log', logSchema);

module.exports = Log;

这就是我的活动日志文档的样子。

{
  "_id": "62788f467a6d842face8a698",
  "activityType": "delete",
  "activitySubject": {
  "id": "627557836752492b6c7ff515",
  "name": "S Thomson",
  "nic": "78456123442"
  },
  "activityPerformedUserId": "6276ab95eb9e634310ea37f8",
  "createdAt": "2022-05-09T03:49:26.510Z",
  "updatedAt": "2022-05-09T03:49:26.510Z"
}

这就像

const a =  {
  "_id": "62788f467a6d842face8a698",
  "activityType": "delete",
  "activitySubject": {
    "id": "627557836752492b6c7ff515",
    "name": "S Thomson",
    "nic": "78456123442"
  },
  "activityPerformedUserId": "6276ab95eb9e634310ea37f8",
  "createdAt": "2022-05-09T03:49:26.510Z",
  "updatedAt": "2022-05-09T03:49:26.510Z"
}

尝试这个:

a.splice(a.findIndex(e => new Date(e.createdAt + 2592000000 ) > new Date()),1);
console.log(a);

MongoDB 将记录删除到粒度级精度的最佳功能是TTL

创建一个字段,在该时间过后将删除整个文档。 例如,如果要在 x 天 y 小时 z 分钟删除记录,则将 TTL 字段的值设置为xyz

在您的情况下,您可以将TTL字段设置为createdAt + 90 天,这样它将在 90 天后从createdAt值中删除

暂无
暂无

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

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