Update using mongoose if time till last update is a certain duration

时间:2015-05-12 23:22:16

标签: node.js mongodb express mongoose

I am kind of stumped on this and is having trouble coming up with ideas on how to deal with this. Say I want to update a variable (say an expire variable) on the database if certain specific entry or entries are not updated (for example, if the database for John's currency is set to 0 for 10 days or more, change a field called bankrupt to true).

I want to do this with express and mongoose. There are some ways I thought of doing this (like continuously checking by some way and to keep a date variable that gets updated every time a value is changed). However, I am not sure if there are better ways to do this. Any advice?

Thanks

1 个答案:

答案 0 :(得分:1)

首先,在要跟踪的对象上保留lastModified字段。您可以使用mongoose中间件进行设置:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var PersonSchema = new Schema({
    name: String,
    currency: Number,
    currencyModifiedAt: Date
});

PersonSchema.pre('save', function(next) {
    // Only update currencyModifiedAt when currency changes
    if (this.isModified('currency')) {
        this.currencyModifiedAt = new Date();
    }
    next();
});

var Person = mongoose.model('Person', PersonSchema);

现在,您可以在X时间内查询其货币字段尚未修改的所有对象。例如:

var moment = require('moment');
var through = require('through');

var thresholdDate = moment().subtract(7, 'days').toDate();

// Find everyone whose currency hasn't changed in 7 days
Person.find({
    currencyModifiedAt: {
        $lt: thresholdDate
    }
}).stream().pipe(through(
    function(person) {
        console.log('Found a person:', person);
    },
    function() {
        console.log('Done');
    }));

现在,您可以按照常规时间表,每天或每小时运行此检查,无论您希望检查的详细程度如何。