diff --git a/dao/user.go b/dao/user.go index ab8a160..436a378 100644 --- a/dao/user.go +++ b/dao/user.go @@ -5,8 +5,8 @@ import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" "gorm.io/gorm" - "log" ) type User struct { @@ -297,11 +297,16 @@ func CreateUserUIConfigInfo(config proto.UserUIConfigInfo) (string, error) { return "", err } fmt.Println("Inserted a single document:", res.InsertedID) - return res.InsertedID.(string), nil + // 类型安全转换 + insertedID, ok := res.InsertedID.(primitive.ObjectID) + if !ok { + return primitive.NilObjectID.String(), fmt.Errorf("意外的ID类型: %T", res.InsertedID) + } + return insertedID.String(), nil } func GetUserUIConfigInfo(userID int) (proto.UserUIConfigInfo, error) { - log.Println("get user ui config info database:", proto.Config.MONGO_DATABASE, " collection:", UserUIConfigCollection) + //log.Println("get user ui config info database:", proto.Config.MONGO_DATABASE, " collection:", UserUIConfigCollection) collection := mongoClient.Database(proto.Config.MONGO_DATABASE).Collection(UserUIConfigCollection) var config proto.UserUIConfigInfo err := collection.FindOne(context.TODO(), bson.M{"user_id": userID}).Decode(&config) diff --git a/service/userService.go b/service/userService.go index eb01e5d..f489b14 100644 --- a/service/userService.go +++ b/service/userService.go @@ -464,7 +464,15 @@ func GetUserUIConfigInfo(userID int) proto.UserUIConfigInfo { userConfig, err := dao.GetUserUIConfigInfo(userID) if err != nil { log.Println("GetUserUIConfigInfo error:", err) - return proto.UserUIConfigInfo{} + } else { + userConfig.UserID = userID + //没有则插入 + id, err2 := dao.CreateUserUIConfigInfo(userConfig) + if err2 != nil { + log.Println("InsertUserUIConfigInfo error:", err.Error()) + } else { + log.Println("InsertUserUIConfigInfo success, id:", id, "config:", userConfig) + } } return userConfig } @@ -475,14 +483,13 @@ func SetUserUIConfigInfo(userID int, config proto.UserUIConfigInfo) error { userConfig, err := dao.GetUserUIConfigInfo(userID) if err != nil { log.Println("SetUserUIConfigInfo error:", err) - return err } config.UserID = userID if userConfig.UserID == 0 { //没有则插入 id, err2 := dao.CreateUserUIConfigInfo(config) if err2 != nil { - log.Println("InsertUserUIConfigInfo error:", err) + log.Println("InsertUserUIConfigInfo error:", err.Error()) return err } else { log.Println("InsertUserUIConfigInfo success, id:", id, "config:", config)