Is there a way to update a document when date is expired in mongodb?

戏子无情 提交于 2021-01-29 10:47:33

问题


I have read some solutions and wonder if I can update (not delete) a document in mongodb if the date is expired after 2 days. Like this.

date:2019-02-15
status:not expired

After 2 days update the status into expired. Here is my code for posting a document.

var bloodstock = new Bloodstock(); 
bloodstock.date = new Date();
bloodstock.status = "not expired"; 
bloodstock.save(function(err) {});

回答1:


Run a cron at daily midnight to compare the date. If the date exists 2 days update the status on the database.

var CronJob = require('cron').CronJob;
const job = new CronJob('00 00 00 * * *', function () {
    if (Date.parse(today_date) > Date.parse(new Date(db_date).getTime() + (2 * 24 * 60 * 60 * 1000))) {
        //Update your status
        ...
    }
});
job.start();

Note : Date comparison can be done either on the MongoDB query or Javascript,It depends on the size of document you need to update.



来源:https://stackoverflow.com/questions/54701819/is-there-a-way-to-update-a-document-when-date-is-expired-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!