【问题标题】:Mongoose - Set TTL on MongoDB DocumentMongoose - 在 MongoDB 文档上设置 TTL
【发布时间】:2021-01-24 00:51:01
【问题描述】:

当在 MongoDB 中创建文档时,我试图通过 mongoose 设置 TTL,但我的任何尝试都没有运气。我的项目中正在使用最新版本的猫鼬,据我所知,我已经在 SO 和其他地方在线尝试了最常见的答案。

我的架构

const mongoose = require('mongoose');

const jobSchema = new mongoose.Schema(
    {
        positionTitle: {
            type: String,
        },
        description: {
            type: String,
        }
    });

const Jobs = mongoose.model('job', jobSchema);

module.exports = Jobs;

我已尝试根据this 问题答案添加一个 createdAt 过期时间:

const jobSchema = new mongoose.Schema({
    positionTitle: {
        type: String,
    },
    description: {
        type: String,
    },
    createdAt: { type: Date, expires: 3600 },
});

除了这个选项,它也在同一个问题中,通过时间戳自动创建:

const jobSchema = new mongoose.Schema(
    {
        positionTitle: {
            type: String,
        },
        description: {
            type: String,
        },
    },
    { timestamps: true }
);

尝试以下变体来设置定义了时间戳的索引:
jobSchema.index({ createdAt: 1 }, { expires: 86400 });
jobSchema.index({ createdAt: 1 }, { expires: '1 day' });
jobSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });

无论我尝试哪个选项,在 MongoDB 的 60 秒周期后,当在文档上设置 createdAt 字段时,文档都会被删除。真的很想知道我做错了什么。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在尝试了您提到的线程中的所有解决方案后,它们都没有奏效。最后,这段代码成功了。它涉及将 expireAt 字段设置为您希望将其删除的实际时间,这真的很有意义。

    const Schema = mongoose.Schema;
    
    const YourSchema = new Schema({
     expireAt: {
       type: Date,
       default: Date.now() + 10 * 60 * 1000   // expires in 10 minutes
     },
    });
    

    这是唯一有效的方法,我尝试的所有其他解决方案总是在 1 分钟后删除,无论我添加了多少时间。

    【讨论】:

      【解决方案2】:

      我也遇到过这个问题。我在这里找到了这个线程https://github.com/Automattic/mongoose/issues/2459,它对我有用。翻译成你的代码应该是这样的。

      const mongoose = require('mongoose');
      
      
      
         const jobSchema = new mongoose.Schema(
              {
                  positionTitle: {
                      type: String,
                  },
                  description: {
                      type: String,
                  },
                  expireAt: {
                      type: Date,
                      default: Date.now,
                      index: { expires: '5s' }
                  }
      
             });
          
      const Jobs = mongoose.model('job', jobSchema);
      
      module.exports = Jobs;
      

      在我添加的链接上,这是最后一个解决方案。我不确定这是在做什么,但这里是 mongo 链接,它应该为其他有此问题的人做些什么。 https://docs.mongodb.com/manual/tutorial/expire-data/。要更改您需要文档的时间量,只需更改过期时间。它肯定接受“#s”和“#d”。此外,如果您希望在特定时间删除您的文档,那么您可以这样做。

      expireAt: {
         type: Date,
         default: new Date('July 22, 2013 14:00:00'),
         index: { expires: '0s' }
      }
      

      这将在指定日期后 0 秒删除文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-08
        • 1970-01-01
        • 1970-01-01
        • 2013-12-27
        • 2013-09-14
        • 2016-04-20
        • 2014-05-13
        相关资源
        最近更新 更多