package model import ( "context" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stores/mon" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "time" ) var _ CommentModel = (*customCommentModel)(nil) type ( // CommentModel is an interface to be customized, add more methods here, // and implement the added methods in customCommentModel. CommentModel interface { commentModel DeleteMany(ctx context.Context, id ...string) (int64, error) UpdateOptional(ctx context.Context, data *Comment) (*mongo.UpdateResult, error) Find(ctx context.Context, param *QueryCommentModelReq) ([]*Comment, int64, error) } customCommentModel struct { *defaultCommentModel } QueryCommentModelReq struct { PostID string PageSize int64 PageIndex int64 } ) func (xw customCommentModel) Find(ctx context.Context, param *QueryCommentModelReq) ([]*Comment, int64, error) { // TODO implement me panic("implement me") } // NewCommentModel returns a model for the mongo. func NewCommentModel(url, db, collection string) CommentModel { conn := mon.MustNewModel(url, db, collection) return &customCommentModel{ defaultCommentModel: newDefaultCommentModel(conn), } } func (m *defaultCommentModel) DeleteMany(ctx context.Context, id ...string) (int64, error) { objectIDs := make([]primitive.ObjectID, 0, len(id)) // prepare for _, item := range id { oid, err := primitive.ObjectIDFromHex(item) if err != nil { logx.WithCallerSkip(1).WithFields( logx.Field("func", "defaultPostModel.DeleteMany"), logx.Field("id", item), ).Error(err.Error()) continue } objectIDs = append(objectIDs, oid) } // 檢查是否有有效的 ObjectIDs if len(objectIDs) == 0 { return 0, ErrNotFound } // 刪除文檔 res, err := m.conn.DeleteMany(ctx, bson.M{"_id": bson.M{"$in": objectIDs}}) if err != nil { return 0, err } return res, err } func (m *defaultCommentModel) UpdateOptional(ctx context.Context, data *Comment) (*mongo.UpdateResult, error) { update := bson.M{"$set": bson.M{}} if data.Content != "" { update["$set"].(bson.M)["content"] = data.Content } if data.LikeCount != -1 { update["$set"].(bson.M)["like_count"] = data.LikeCount } if data.DisLikeCount != -1 { update["$set"].(bson.M)["dis_like_count"] = data.DisLikeCount } // UpdateAt 是每次都需要更新的,不用檢查 update["$set"].(bson.M)["updateAt"] = time.Now().UTC().UnixNano() res, err := m.conn.UpdateOne(ctx, bson.M{"_id": data.ID}, update) return res, err }