首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >mongodb每10分钟运行一次函数

mongodb每10分钟运行一次函数
EN

Stack Overflow用户
提问于 2017-12-30 15:48:09
回答 2查看 96关注 0票数 0

我在mongodb中有一个文档,如下所示:

代码语言:javascript
运行
复制
{
    id:1,
    requestType: {
        "api1": { 
            count:1,
            firstAttemptTime: 1514360898751.0
        },
        "api2": { 
            count:4,
            firstAttemptTime: 1514366897751.0
        }
    }
}

我想用mongoose写一个函数,它每10分钟调用一次,根据firstAttemptTime键从requestType中删除一个对象。例如,10分钟后,文档应如下所示:

代码语言:javascript
运行
复制
{
    id:1,
    requestType: {
        "api2": { 
            count:4,
            firstAttemptTime: 1514366897751.0
        }
    }
}
EN

回答 2

Stack Overflow用户

发布于 2017-12-30 16:04:25

看起来你想删除基于时间戳的数据。在MongoDB中,可以通过为记录设置TTL来实现这一点,这样就不需要定期运行函数。您只需创建TTL索引,并指定文档应该在多少秒后删除。下面是关于此https://docs.mongodb.com/manual/tutorial/expire-data/的教程

票数 1
EN

Stack Overflow用户

发布于 2017-12-30 16:07:22

像这样的东西就行了

代码语言:javascript
运行
复制
var mongoose = require('mongoose')
var db = mongoose.createConnection('mongodb://localhost:port/db')
var newSchema = new mongoose.Schema({
    id: Number,
    requestType: { type: {} },
    requestTypeList: { type: [] },
})
var model = db.model('newModel', newSchema)

setTimeout(function(){
    model.find({id: 1}, function(err, doc){
        // remove requestType properties first keyed value
        delete Object.keys(doc.requestType)[0]

        // or

        // remove requestType property's first value as an Array
        delete doc.requestTypeList[0] // I'd recomend because otherwise you'll be left with ever increasing key values like api90000000+ as the first key

        doc.save(function(err){
            if(!err){
                console.log('success :)')
            } else {
                console.log('oh oh')
            }
        })

    })
}, 600000) // 600000ms == 10 minutes

// es 5 or 6 idk..

setTimeout(()=>{
    model.find({id: 1}, (err, doc)=>{
        // remove requestType properties first keyed value
        delete Object.keys(doc.requestType)[0]

        // or

        // remove requestType property's first value as an Array
        delete doc.requestTypeList[0] // I'd recomend because otherwise you'll be left with ever increasing key values like api90000000+ as the first key

        doc.save((err)=>{
            if(!err){
                console.log('success :)')
            } else {
                console.log('oh oh')
            }
        })

    })
}, 600000) // 600000ms == 10 minutes

但我认为Priidik的TTL答案可能更可靠

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48032037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档