我在mongodb中有一个文件如下:
{
id:1,
requestType: {
"api1": {
count:1,
firstAttemptTime: 1514360898751.0
},
"api2": {
count:4,
firstAttemptTime: 1514366897751.0
}
}
}
我想在mongoose中编写一个函数,它根据firstAttemptTime键每隔10分钟调用一次从requestType中删除一个对象。例如,10分钟后文件应如下:
{
id:1,
requestType: {
"api2": {
count:4,
firstAttemptTime: 1514366897751.0
}
}
}
您似乎想要根据时间戳删除数据。通过为记录设置TTL,可以在MongoDB中执行此操作,然后无需定期运行函数。您只需创建TTL索引并指定应删除文档的秒数。有关于这个https://docs.mongodb.com/manual/tutorial/expire-data/的教程
像这样的东西会起作用
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答案可能更可靠