我在mongodb中有一个文档,如下所示:
{
id:1,
requestType: {
"api1": {
count:1,
firstAttemptTime: 1514360898751.0
},
"api2": {
count:4,
firstAttemptTime: 1514366897751.0
}
}
}
我想用mongoose写一个函数,它每10分钟调用一次,根据firstAttemptTime键从requestType中删除一个对象。例如,10分钟后,文档应如下所示:
{
id:1,
requestType: {
"api2": {
count:4,
firstAttemptTime: 1514366897751.0
}
}
}
发布于 2017-12-30 16:04:25
看起来你想删除基于时间戳的数据。在MongoDB中,可以通过为记录设置TTL来实现这一点,这样就不需要定期运行函数。您只需创建TTL索引,并指定文档应该在多少秒后删除。下面是关于此https://docs.mongodb.com/manual/tutorial/expire-data/的教程
发布于 2017-12-30 16:07:22
像这样的东西就行了
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答案可能更可靠
https://stackoverflow.com/questions/48032037
复制相似问题