【问题标题】:How do I reset the expiration date of a document in Mongoose?如何在 Mongoose 中重置文档的到期日期?
【发布时间】:2016-02-24 00:01:27
【问题描述】:

根据this post 中的答案,我创建了以下文档架构,它将创建的每个新文档设置为在创建后 24 小时后过期:

var mongoose = require('./node_modules/mongoose');
mongoose.connect(mongodburi, {
    server : {
        socketOptions : {
            keepAlive: 1
        }
    },
    replset : {
        socketOptions : {
            keepAlive: 1
        }
    }
});
var sessionSchema = mongoose.Schema({
    uid: {
        type: String,
        required: true,
        unique: true
    },
    token: {
        type: String,
        required: false,
        unique: true
    },
    createdAt: { 
        type: Date, 
        default: Date.now,
        expires: 24*60*60
    }
});

var Session = mongoose.model('Session', sessionSchema);

我希望能够将文档的过期时间再设置 24 小时。这是这样做的方法吗(?):

Session.update({uid: someUID}, {createdAt: Date.now}, null, function (err, numOfSessionsUpdated)
{
   if (numOfSessionsUpdated > 0)
   {
      console.log('session expiration has been postponed for another 24 hours');
   }    
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这很接近,但您需要调用 Date.now 而不是仅仅将其作为函数传递:

    Session.update({uid: someUID}, {createdAt: Date.now()}, null, function (err, numOfSessionsUpdated)
    {
       if (numOfSessionsUpdated > 0)
       {
          console.log('session expiration has been postponed for another 24 hours');
       }    
    });
    

    【讨论】:

    • 我明白了,谢谢!我很困惑,因为在 Schema 构造函数中您没有调用该函数(对于 createdAt 键),但我认为这是因为,在 schema 构造函数中,您只需指出在需要调用的时候需要调用什么函数要创建的新文档。
    猜你喜欢
    • 2014-08-08
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多