Limit N documents per user for a specific Schema

Viewed 38

I think it would be easier for me to explain starting with an example.

Let's say we have this Schema:

var entrySchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    user: {
        type: String,
        ref: User
    },
    // more fields here
    });

So basically there is a 1:M kind of relationship where a user can have multiple entries stored in the DB.

Now for optimization's sake and to reduce costs I would like to only allow N (50-100) entries to be stored for a specific user.

Of course, the trivial solution would be to check each time I add an entry for a user if the limit has been reached and delete the oldest entry.

I was wondering if there is any built-in mechanism to make this easier to implement. I'm not saying it's hard to implement, just that it looks like something that maybe could be solved with a feature of mongo/mongoose that I'm not aware of.

I'm having a hard time finding anything in both mongo documentation and mongoose. Note an npm package is welcome too.

0 Answers
Related