MongoDB TTL到期在NodeJS上无法正常工作

时间:2017-12-13 08:26:15

标签: node.js mongodb caching ttl

我使用MongoDB(v3.4)作为缓存并使用TTL索引使记录失效。但是,TTL设置似乎无法正常工作。具体来说,我使用端点测试插入数据(如下所示)。

端点mongoInsert应该在5分钟后到期。然而,似乎在约1分钟后,该文件被删除。我已经使用moment()。utc()。toDate()查找了有关使用UTC时间的其他类似建议,行为是相同的。新的Date()返回UTC时间,所以我猜它应该是相同的效果。

不确定是否应包含其他设置,但文档中未详细说明。有没有人遇到过这个?

function mongoInsert(mongoClient){
    return function(req, res){
        mongoClient.connect('mongodb://localhost:27017/cache', function(err, db) {
            db.collection('data', function(err, collection){
                var testItems = [{
                    "_id": "abc12345",
                    "dmac": "abc",
                    "createdAt": new Date(),
                    "val": {
                        "0": 10,
                        "1": 15,
                        "2": 5
                    },
                    "res": "minutes",
                    "time": "2017-12-04T00:12:58Z"
                }];
                let unix = new moment().valueOf();
                collection.createIndex({createdAt: unix}, {expireAfterSeconds: 300});
                collection.insertMany(testItems, function(err, items){
                    db.close();
                    res.json(items);
                });
            })
        })
    }
}

1 个答案:

答案 0 :(得分:1)

collection.createIndex({createdAt: 1}, {expireAfterSeconds: 60,unique:true});

collection.createIndex({createdAt: 1}, {expireAfterSeconds: 300,unique:true});

这是无效的

您不能使用createIndex()来更改现有索引的expireAfterSeconds值。而是将collMod数据库命令与索引集合标志结合使用。否则,要更改现有索引的选项的值,必须先删除索引并重新创建。

https://docs.mongodb.com/v3.4/core/index-ttl/

对于单个文档的到期,有报告称只能通过计算到期时间并按特定时钟时间到期来完成(参见:groups.google.com/forum/#!topic/mongodb-dev/ ZLb8KSrLyOo)。

var testItems = [{
    "_id": "abc12345",
    "dmac": "abc",
    "expireAt": moment().add(3, 'minutes').toDate(),
    "val": {
        "0": 10,
        "1": 15,
        "2": 5
    },
    "res": "minutes",
    "time": "2017-12-04T00:12:58Z"
}];
let unix = new moment().valueOf();
collection.createIndex({expireAt: unix}, {expireAfterSeconds: 0}, function(error, indexName){
    if(error) console.log(error);
    console.log(indexName);  
});
相关问题