Mongoose - change ttl for one document

I have a very specific thing that I want to accomplish, and I wanted to make sure that this is not possible in mongoose / mongoDB before I go and kill it all myself. I checked mongoose-ttl for nodejs and several forums and did not find absolutely what I need. there he is:

I have a schema with a createDate date field. Now I want to put the TTL in this field, so good that I can do it like this (expiration after 5000 seconds): createDate: {type: Date, default: Date.now, expires: 5000}

but I would like my users to be able to "vote" for documents that they like, so that these documents will receive a longer period of time for life, without changing other documents in my collection. So, can I somehow change the TTL of one document as soon as the user tells me that he likes this document using mongoose or other existing npm related modules?

Thank you

+4
source share
2 answers

More than a year has passed, but it may be useful for others, so here is my answer:

I tried to perform the same task in order to resolve the grace period after deleting the record so that the user could subsequently cancel the operation.

, TTL .

, expireAfterSeconds :

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

- , expireAfterSeconds :

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

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 });

moment

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;
};

moment

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;
};
+9

Source: https://habr.com/ru/post/1529483/


All Articles