广告素材增加排序字段
advitise_info 增加 sort 字段,列表默认按 sort 从小到大排序。 info/list 增加 orderBy 参数: sortAsc(默认) / sortDesc / newest, 三种排序末尾都追加 _id 作为最后一级,避免同值文档在分页时重复或漏数据。 启动时回填历史数据缺失的 sort 字段: 缺字段的文档在升序里会排在 0 之前, 且按 sort=0 精确查询查不到。用 UpdateMMany 避免刷新全表 updatedAt。 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -31,7 +31,7 @@ func InfoList(ctx context.Context, req *proto.AdvitiseInfoListReq) (*proto.Advit
|
||||
return nil, err
|
||||
}
|
||||
opt := &options.FindOptions{}
|
||||
opt.SetSort(bson.D{{Key: advitiseInfoMod.FN.AdvitiseInfo.CreatedAt, Value: -1}})
|
||||
opt.SetSort(infoListOrder(req.OrderBy))
|
||||
opt.SetSkip((req.PageNum - 1) * req.PageSize)
|
||||
opt.SetLimit(req.PageSize)
|
||||
list, err := advitiseInfoMod.FindManyAdvitiseInfos(ctx, filter, opt)
|
||||
@@ -43,6 +43,39 @@ func InfoList(ctx context.Context, req *proto.AdvitiseInfoListReq) (*proto.Advit
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 列表排序方式
|
||||
const (
|
||||
OrderBySortAsc = "sortAsc" // 排序值从小到大(默认)
|
||||
OrderBySortDesc = "sortDesc" // 排序值从大到小
|
||||
OrderByNewest = "newest" // 按创建时间,最新在前
|
||||
)
|
||||
|
||||
// infoListOrder 把排序方式翻成 mongo 的 sort 文档。
|
||||
// 末尾一律追加 _id 作为最后一级,sort/createdAt 相同的文档顺序才是确定的,
|
||||
// 否则 skip/limit 翻页会出现重复或漏数据。
|
||||
func infoListOrder(orderBy string) bson.D {
|
||||
fn := advitiseInfoMod.FN.AdvitiseInfo
|
||||
switch orderBy {
|
||||
case OrderBySortDesc:
|
||||
return bson.D{
|
||||
{Key: fn.Sort, Value: -1},
|
||||
{Key: fn.CreatedAt, Value: -1},
|
||||
{Key: fn.Id, Value: -1},
|
||||
}
|
||||
case OrderByNewest:
|
||||
return bson.D{
|
||||
{Key: fn.CreatedAt, Value: -1},
|
||||
{Key: fn.Id, Value: -1},
|
||||
}
|
||||
default: // OrderBySortAsc 及未传值
|
||||
return bson.D{
|
||||
{Key: fn.Sort, Value: 1},
|
||||
{Key: fn.CreatedAt, Value: -1},
|
||||
{Key: fn.Id, Value: -1},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func InfoAdd(ctx context.Context, req *proto.AddAdvitiseInfoReq) error {
|
||||
now := time.Now()
|
||||
doc := &advitiseInfoMod.AdvitiseInfo{
|
||||
@@ -60,6 +93,7 @@ func InfoAdd(ctx context.Context, req *proto.AddAdvitiseInfoReq) error {
|
||||
RandomNames: emptyIfNil(req.RandomNames),
|
||||
Link: req.Link,
|
||||
Status: req.Status,
|
||||
Sort: req.Sort,
|
||||
StartTime: req.StartTime,
|
||||
EndTime: req.EndTime,
|
||||
Remark: req.Remark,
|
||||
@@ -113,6 +147,9 @@ func InfoUpdate(ctx context.Context, req *proto.UpdateAdvitiseInfoReq) error {
|
||||
if req.Status != nil {
|
||||
set[advitiseInfoMod.FN.AdvitiseInfo.Status] = *req.Status
|
||||
}
|
||||
if req.Sort != nil {
|
||||
set[advitiseInfoMod.FN.AdvitiseInfo.Sort] = *req.Sort
|
||||
}
|
||||
if req.StartTime != nil {
|
||||
set[advitiseInfoMod.FN.AdvitiseInfo.StartTime] = *req.StartTime
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user