亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何注冊不同集合的 ID

如何注冊不同集合的 ID

Go
嚕嚕噠 2022-09-26 14:50:36
我正在做一個用于銷售和創建視頻游戲的應用程序的實踐,該應用程序的用戶將具有僅由管理員分配的多個角色,為此我有兩個集合,一個將存儲所有角色,另一個用于用戶,但我遇到問題,這是如何獲取角色的ID, 我能想到的唯一方法是在我的用戶模型中有一部分字符串,通過搜索角色名稱來保存id,但這種方式不正確,因為它不保存對象的ID。這是我的榜樣角色和用戶:type Role struct {    ID        primitive.ObjectID `bson:"_id,omitempty" json:"id"`    Name      string             `bson:"name,omitempty"`    State     bool               `bson:"state,omitempty"`    CreatedAt time.Time          `bson:"created_at,omitempty" json:"created_at"`    UpdatedAt time.Time          `bson:"updated_at,omitempty" json:"updated_at"`}type User struct {    ID        primitive.ObjectID `bson:"_id,omitempty" json:"id"`    FirstName string             `bson:"first_name,omitempty" json:"first_name"`    LastName  string             `bson:"last_name,omitempty" json:"last_name"`    Email     string             `bson:"email,omitempty" json:"email"`    Password  string             `bson:"Password,omitempty" json:"Password"`    Avatar    string             `bson:"avatar,omitempty" json:"avatar"`    Role      []string           `bson:"role,omitempty" json:"role"`    CreatedAt time.Time          `bson:"created_at,omitempty" json:"created_at"`    UpdatedAt time.Time          `bson:"updated_at,omitempty" json:"updated_at"`}這是我的創建用戶:func CreateUser(w http.ResponseWriter, r *http.Request) {    w.Header().Set("Content-Type", "application/json")    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)    defer cancel()    collection := storage.Connection().Database("testing")    collectionRole := collection.Collection("roles")    collectionUser := collection.Collection("users")    u := &model.User{}    if err := json.NewDecoder(r.Body).Decode(u); err != nil {        http.Error(w, "format incorrect", http.StatusBadRequest)        return    }    var rl []model.Role    var roles []string    cursor, err := collectionRole.Find(ctx, bson.D{{"name", bson.D{{"$in", u.Role}}}})    if err != nil {        http.Error(w, "collection not found ", 404)        return    }
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

我的用戶模型中的字符串的一部分,它通過搜索角色名稱來保存id,但以這種方式不正確,因為它不保存對象的ID。

嘗試存儲對象 ID 而不是角色字符串名稱。因為這將允許您更改角色的名稱,而無需更新所有用戶集合。

您可以存儲基元。對象 ID 按原樣,或使用對象 ID.Hex() 和對象 ID從十六進制() 方法存儲十六進制字符串。


查看完整回答
反對 回復 2022-09-26
  • 1 回答
  • 0 關注
  • 79 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號