mongoose - change ttl for a single document

前端 未结 2 1611
抹茶落季
抹茶落季 2020-12-17 05:22

I have a very certain thing i want to accomplish, and I wanted to make sure it is not possible in mongoose/mongoDB before I go and code the whole thing myself. I checked mon

相关标签:
2条回答
  • 2020-12-17 05:38

    You could use the expire at clock time feature in mongodb. You will have to update the expire time each time you want to extend the expiration of a document.

    http://docs.mongodb.org/manual/tutorial/expire-data/#expire-documents-at-a-certain-clock-time

    0 讨论(0)
  • 2020-12-17 05:44

    It has been more than a year, but this may be useful for others, so here is my answer:

    I was trying accomplish this same thing, in order to allow a grace period after an entry deletion, so the user can cancel the operation afterwards.

    As stated by Mike Bennett, you can use a TTL index making documents expire at a specific clock time.

    Yo have to create an index, setting the expireAfterSeconds to zero:

    db.yourCollection.createIndex({ "expireAt": 1 }, { expireAfterSeconds: 0 });
    

    This will not affect any of the documents in your collection, unless you set expireAfterSeconds on a particular document like so:

    db.log_events.insert( {
       "expireAt": new Date('July 22, 2013 14:00:00'),
       "logEvent": 2,
       "logMessage": "Success!"
    } )
    

    Example in mongoose

    Model

    var BeerSchema = new Schema({
      name: {
        type: String,
        unique: true,
        required: true
      },
      description: String,
      alcohol: Number,
      price: Number,
      createdAt: { type: Date, default: Date.now }
      expireAt: { type: Date, default: undefined } // you don't need to set this default, but I like it there for semantic clearness
    });
    
    BeerSchema.index({ "expireAt": 1 }, { expireAfterSeconds: 0 });
    

    Deletion with grace period

    Uses moment for date manipulation

    exports.deleteBeer = function(id) {
      var deferred = q.defer();
    
      Beer.update(id, { expireAt: moment().add(10, 'seconds') }, function(err, data) {
        if(err) {
          deferred.reject(err);
        } else {
          deferred.resolve(data);
        }
      });
      return deferred.promise;
    };
    

    Revert deletion

    Uses moment for date manipulation

    exports.undeleteBeer = function(id) {
      var deferred = q.defer();
      // Set expireAt to undefined
      Beer.update(id, { $unset: { expireAt: 1 }}, function(err, data) {
        if(err) {
          deferred.reject(err);
        } else {
          deferred.resolve(data);
        }
      });
      return deferred.promise;
    };
    
    0 讨论(0)
提交回复
热议问题