app-cloudep-member-server/internal/model/mongo/auto_id_model.go

51 lines
1.3 KiB
Go

package model
import (
"context"
"time"
"github.com/zeromicro/go-zero/core/stores/mon"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
var _ AutoIdModel = (*customAutoIdModel)(nil)
type (
// AutoIdModel is an interface to be customized, add more methods here,
// and implement the added methods in customAutoIdModel.
AutoIdModel interface {
autoIdModel
Inc(ctx context.Context, data *AutoId) error
}
customAutoIdModel struct {
*defaultAutoIdModel
}
)
// NewAutoIdModel returns a model for the mongo.
func NewAutoIdModel(url, db, collection string) AutoIdModel {
conn := mon.MustNewModel(url, db, collection)
return &customAutoIdModel{
defaultAutoIdModel: newDefaultAutoIdModel(conn),
}
}
func (m *customAutoIdModel) Inc(ctx context.Context, data *AutoId) error {
// 定義查詢的條件
filter := bson.M{"name": "auto_id"}
// 定義更新的操作,包括自增和更新時間
update := bson.M{
"$inc": bson.M{"counter": 1}, // 自增 counter
"$set": bson.M{"updateAt": time.Now().UTC()}, // 設置 updateAt 為當前時間
}
// 使用 FindOneAndUpdate 並將結果解碼到 data 中
err := m.conn.FindOneAndUpdate(ctx, &data, filter, update,
options.FindOneAndUpdate().SetUpsert(true),
options.FindOneAndUpdate().SetReturnDocument(options.After))
return err
}