如何注册不同集合的ID

huangapple go评论153阅读模式
英文:

how to register the id of a different collection

问题

我正在进行一个关于销售和创建视频游戏的应用程序的练习,应用程序的用户将拥有多个角色,这些角色仅由管理员分配。为此,我有两个集合,一个用于存储所有角色,另一个用于存储用户。但我遇到了一个问题,就是如何获取角色的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, "格式不正确", 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, "集合未找到", 404)
        return
    }

    if err := cursor.All(ctx, &rl); err != nil {
        log.Fatal(err.Error())
        return
    }

    for _, rol := range rl {
        roles = append(roles, rol.ID.Hex())
    }

    result, err := collectionUser.InsertOne(ctx, bson.D{
        {"first_name", u.FirstName},
        {"role", roles},
    })
    if err != nil {
        log.Fatal(err.Error())
        return
    }

    json.NewEncoder(w).Encode(result)
}

希望对你有帮助!

英文:

I am doing a practice of an application for the sale and creation of video games, the users of the application will have multiple roles which are assigned only by the administrator, for that I have two collections, one where all the roles will be stored and another for the users , but I am encountering problem and it is how to get the id of the roles, the only way I can think of is to have a portion of string in my user model that saves the id by searching by means the role name, but not in this way is correct because it does not save the ID of the object.<br/>
This my model role and user:

type Role struct {
ID        primitive.ObjectID `bson:&quot;_id,omitempty&quot; json:&quot;id&quot;`
Name      string             `bson:&quot;name,omitempty&quot;`
State     bool               `bson:&quot;state,omitempty&quot;`
CreatedAt time.Time          `bson:&quot;created_at,omitempty&quot; json:&quot;created_at&quot;`
UpdatedAt time.Time          `bson:&quot;updated_at,omitempty&quot; json:&quot;updated_at&quot;`
}
type User struct {
ID        primitive.ObjectID `bson:&quot;_id,omitempty&quot; json:&quot;id&quot;`
FirstName string             `bson:&quot;first_name,omitempty&quot; json:&quot;first_name&quot;`
LastName  string             `bson:&quot;last_name,omitempty&quot; json:&quot;last_name&quot;`
Email     string             `bson:&quot;email,omitempty&quot; json:&quot;email&quot;`
Password  string             `bson:&quot;Password,omitempty&quot; json:&quot;Password&quot;`
Avatar    string             `bson:&quot;avatar,omitempty&quot; json:&quot;avatar&quot;`
Role      []string           `bson:&quot;role,omitempty&quot; json:&quot;role&quot;`
CreatedAt time.Time          `bson:&quot;created_at,omitempty&quot; json:&quot;created_at&quot;`
UpdatedAt time.Time          `bson:&quot;updated_at,omitempty&quot; json:&quot;updated_at&quot;`
}

This my create user:

func CreateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
collection := storage.Connection().Database(&quot;testing&quot;)
collectionRole := collection.Collection(&quot;roles&quot;)
collectionUser := collection.Collection(&quot;users&quot;)
u := &amp;model.User{}
if err := json.NewDecoder(r.Body).Decode(u); err != nil {
http.Error(w, &quot;format incorrect&quot;, http.StatusBadRequest)
return
}
var rl []model.Role
var roles []string
cursor, err := collectionRole.Find(ctx, bson.D{{&quot;name&quot;, bson.D{{&quot;$in&quot;, u.Role}}}})
if err != nil {
http.Error(w, &quot;collection not found &quot;, 404)
return
}
if err := cursor.All(ctx, &amp;rl); err != nil {
log.Fatal(err.Error())
return
}
for _, rol := range rl {
roles = append(roles, rol.ID.Hex())
}
result, err := collectionUser.InsertOne(ctx, bson.D{
{&quot;first_name&quot;, u.FirstName},
{&quot;role&quot;, roles},
})
if err != nil {
log.Fatal(err.Error())
return
}
json.NewEncoder(w).Encode(result)
}

答案1

得分: 1

尝试存储ObjectID而不是角色字符串名称。这样可以在不必更新所有用户集合的情况下更改角色名称。

你可以将primitive.ObjectID直接存储,或者使用ObjectID.Hex()ObjectIDFromHex()方法将其存储为十六进制字符串。

英文:

> a portion of string in my user model that saves the id by searching by means the role name, but not in this way is correct because it does not save the ID of the object.

Try storing the ObjectID instead of the role string name. As this would allow you to alter the role's name without having to update all of the users collection.

You could either store the primitive.ObjectID as is, or store the hex string using ObjectID.Hex() and ObjectIDFromHex() methods.

huangapple
  • 本文由 发表于 2021年5月23日 11:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/67655936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定