【问题标题】:ttl not working in loopback when I set it for a Model当我为模型设置 ttl 时,它不能在环回中工作
【发布时间】:2018-11-26 17:26:41
【问题描述】:

我正在尝试为环回模型设置ttl,以便在指定时间后自动删除文档。 这是我添加的属性:

"ttl": {
    "type": "number",
    "required": true
}

这不是AccessToken 模型,而是一个单独的模型,我希望在指定时间间隔后删除其文档。

【问题讨论】:

    标签: loopbackjs loopback


    【解决方案1】:

    AccessTokens 在他们的ttl 启动后不会被删除,他们只是为了登录目的而使令牌无效。 我不确定任何数据库/ORM 是否会在它们存在一定时间后删除行我错了mongodb 这样做,但是环回实际上并没有使用此功能。此脚本将创建一个作业,根据其ttl 列删除所有已过期的行。

    server/boot/job-delete-expired.js

    module.exports = (server) => {
        const myModel = server.models.myModel;
    
        if (!myModel) {
            throw new Error("My model not found!");
        }
    
        const deleteExpiredModels = async () => {
            const now = new Date();
            const all = await myModel.find();
            // If the created time + the ttl is paste now then it can be deleted
            const expired = all.filter(m => (m.created + m.ttl) > now);
            // Delete them all
            await Promise.all(expired.map(e => myModel.destroyById(e.id)));
        };
    
        // Execute this every 10 minutes
        setInterval(() => deleteExpiredModels(), 60000)
    };
    

    免责声明:此代码没有错误处理,并且 setInterval 不会等待承诺解决,如果您在生产中使用它,请考虑使用 async/await 的 while 循环,以确保只有一个 deleteExpiredModels 实例曾被处决。

    【讨论】:

    • 谢谢,但mongodb 确实具有在指定时间间隔后自动删除文档的功能。 docs.mongodb.com/manual/tutorial/expire-data 它使用db.collection.createIndex,但我不确定如何通过环回来做到这一点
    • 呃,我不知道。相应地编辑了我的评论。
    【解决方案2】:

    我能够通过以下方式解决这个问题:

    MyCollection.getDataSource().connector.connect(function(err, db) {
        if(!err){
            var collection = db.collection('MyCollection');
            collection.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } );
        }
    
    });
    

    然后对于每个文档,我插入了expireAt,它对应于文档应该过期的时间。 MongoDB 在文档的expireAt 时间自动从集合中删除文档。

    【讨论】:

      【解决方案3】:

      我使用model.json文件解决了这个问题

      "indexes":{
          "expireAt_1":{
              "keys": {"createdOn": 1},
              "options":{"expireAfterSeconds": 2592000}
           }
      }
      

      我为索引使用了一个名称。 定义的键具有具有日期值的对象属性。 expireAfterSeconds 值需要在 options 属性中设置。在这种情况下,我将其设置为 createdOn 日期后 30 天

      【讨论】:

        猜你喜欢
        • 2020-04-09
        • 2023-01-12
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        • 2022-11-26
        • 2021-08-02
        • 2017-12-01
        相关资源
        最近更新 更多