我使用nodejs(v0.8.15)和最新的mongoose
所以,我收集了聊天消息
{ message: String, date: Date, ... }
我需要创建一个查询,删除旧邮件并保留最新消息,例如30。
例如:数据库有50条消息,所以当用户进入聊天时,他将删除20个旧的并留下30个更新的消息; 100条消息 - > 70删除,30离开; 20条消息 - > 0删除,20离开也许唯一的方法是使method
或static
功能,但我不确定。
答案 0 :(得分:0)
您可以尝试这样的事情:
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( );
}
});
};
然后像这样使用它:
Collection.shift_messages( { user : "john" }, function( err ) {
// yay, we're done shifting messages!
});
确保在date
上设置索引以提高.sort
效果。