bstar
bstar

Reputation: 271

Limiting Number of Collection Records in Loopback Model

What I need to do is limit a particular collection (in my case logs) to 100 records. That is, when there are 100 logs and a new one is added, the oldest one is destroyed.

I know I can do this in mongo by setting the capped/size/max values, but I also want to have some code for more advanced query filters down the road.

I'm looking to introduce this as an Operation Hook (http://docs.strongloop.com/display/public/LB/Operation+hooks#Operationhooks-access), but I can't figure out how to query the Model in question and remove the last record if a threshold has been exceeded. Right now I just setup an Access hook that's just checks that the threshold has not been met, if it has it will delete the last record. This would ultimately be done on the "before create" hook, but doing it this way is easier for testing.

Here's some Pseudocode (common/models/log.js):

module.exports = function (Log) {
  Log.observe('access', function logQuery (ctx, next) {

    var threshold = 10;
    var logs = Log.find({});

    if (logs.length > threshold) {
      logs[logs.length].delete // delete last record
    }

    next();
  });
};

This obviously doesn't work, just hoping it gives a clue to what I'm trying to do.

Thanks.

Upvotes: 0

Views: 562

Answers (1)

Jordan Kasper
Jordan Kasper

Reputation: 13273

I think what you're looking for is actually a remote hook and then the PersistedModel's count() method:

module.exports = function(Log) {

  Log.afterRemote('create', function accessCount(ctx, instance, next) {
    console.log('AFTER CREATE of a new Log');

    Log.count(function(err, count) {
        if (err) {
            // let this one go maybe? if not, call: next(err);
        }

        console.log('There are now ' + count + ' Log records.');

        // do whatever you need to here

        next();
    });
  });

};

Upvotes: 0

Related Questions