package usercheckinmod import ( "fmt" "91porn-server/common/db" "91porn-server/common/log" "91porn-server/models" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) const table = models.UserCheckin func coll(t *db.MongoTool) *db.MongoTool { if t == nil { return mdb.Coll(table) } return t.Coll(table) } func initIndex() { many := []mongo.IndexModel{ { Keys: bson.D{{Key: "createdAt", Value: -1}}, }, { Keys: bson.D{{Key: "userId", Value: 1}, {Key: "date", Value: -1}}, Options: options.Index().SetUnique(true), }, { Keys: bson.D{{Key: "userId", Value: 1}}, }, { Keys: bson.D{{Key: "date", Value: -1}}, Options: options.Index().SetExpireAfterSeconds(100 * 24 * 60 * 60), }, } if _, err := coll(nil).CreateIndex(many); err != nil { panic(fmt.Sprintf("%s model set index err ==>[%+v]", table, err)) } } func Init() { mdb = db.Init(table) initIndex() } // InsertOne 插入一个签到记录 func InsertOne(data *UserCheckin) error { if _, err := coll(nil).InsertOne(data); err != nil { log.Error(fmt.Sprintf("[usercheckinmod:InsertOne] failed: %+v", err)) return err } return nil } // FindOne 查找一个签到记录 func FindOne(filter primitive.M) (*UserCheckin, error) { var data UserCheckin if err := coll(nil).FindOne(&data, filter); err != nil { log.Error(fmt.Sprintf("[usercheckinmod:FindOne] failed: %+v", err)) return nil, err } if data.ID.IsZero() { return nil, nil } return &data, nil } // FindMany 查找一批签到记录 func FindMany(filter primitive.M, opts ...*options.FindOptions) (CheckinList, error) { data := make(CheckinList, 0) if err := coll(nil).Find(&data, filter, opts...); err != nil { log.Error(fmt.Sprintf("[usercheckinmod:FindMany] failed: %+v", err)) return nil, err } return data, nil } // UpdateOne 更新一个签到记录 func UpdateOne(filter primitive.M, update primitive.M) error { result, err := coll(nil).UpdateOne(filter, update) if err != nil { log.Error(fmt.Sprintf("[usercheckinmod:UpdateOne] failed: %+v", err)) return err } if result.MatchedCount != 1 { return mongo.ErrNoDocuments } return nil } // Count 统计数量 func Count(filter primitive.M) (int64, error) { count, err := coll(nil).Count(filter) if err != nil { log.Error(fmt.Sprintf("[usercheckinmod:Count] failed: %+v", err)) return 0, err } return count, nil } // DeleteOne 删除一个签到记录 func DeleteOne(filter primitive.M) (int64, error) { result, err := coll(nil).DeleteOne(filter) if err != nil { log.Error(fmt.Sprintf("[usercheckinmod:DeleteOne] failed: %+v", err)) return 0, err } return result.DeletedCount, nil }