mongoose: how to .remove() data and leave given number

i m using nodejs (v0.8.15) and latest mongoose

so, i have collection with messages from chat

{ message: String, date: Date, ... }

i need make a query that removes old messages and leave the newest messages, for example 30.

example: database has 50 messages, so when user enters the chat he will remove 20 old and leave 30 newer; 100 messages -> 70 remove, 30 leave; 20 messages -> 0 remove, 20 leave

maybe the only way is to make method or static function, but i m not sure.

thank you.

You can try something like this:

Collection.statics.shift_messages = function( query, callback ) {
    Collection.find( query, "_id" ).sort( "-date" ).exec( function( err, msgs ) {
        if (err) {
            return callback( err );
        }
        var toRemove = msgs.slice( 30 );
        if (toRemove.length) {
            toRemove = toRemove.map( function(msg) { return msg._id; } );
            Collection.remove({ _id : { $in : toRemove } }, callback );
        } else {
            callback( );
        }
    });
};

and then use it like that:

Collection.shift_messages( { user : "john" }, function( err ) {
    // yay, we're done shifting messages!
});

Make sure to set index on date to increase .sort performance.