更新特定用户字段

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

Updating certain user fields

问题

我的翻译如下:

对我的 API 的请求包含一个必需的 ID 字段,以及可选的其他字段,如姓名、电子邮件和用户名。

{
    "id" : "12345",
    "name" : "Bob",
    "email" : "test@example.com"
}

将请求绑定到一个名为 user 的结构体后,如果我的数据库中没有与该 ID 相对应的用户,我会使用以下代码将其添加到数据库中:

user.App_id = appId
user.Created_at = (*tools.Timestamp)(&now)
user.Updated_at = (*tools.Timestamp)(&now)
_ = C.Database.C("users").Insert(&user)

但是,如果存在该用户,我只想更新请求对象中包含的字段,但我不确定如何编写查询语句。

我的 user 结构体使用指针,以便我可以检查 nil 值。

type user struct {
    Id      *string    `bson:"id" json:"id"`
    Name    *string    `bson:"name" json:"name"`
    ...
}

我在应用程序的其他地方使用的更新查询语句如下所示:

err := collection("users").Update(bson.M{"id" : "user.Id"}, bson.M{"$set": bson.M{"???":"???"}})

但在这种情况下,我不确定如何构建查询语句的后半部分。

注意:我没有使用 MongoDB 的 _id 字段。

英文:

Requests to my API contain an ID (required) and optional others fields such as name, email and username.

{
    "id" : "12345",
    "name" : "Bob",
    "email" : "test@example.com"
}

After binding the request to a struct user if there isn't a user with the ID in my database I add them to it using:

user.App_id = appId
user.Created_at = (*tools.Timestamp)(&now)
user.Updated_at = (*tools.Timestamp)(&now)
_ = C.Database.C("users").Insert(&user);

but if there is a user I only want to update the fields that the request object includes but I'm not sure how to write the query.

My user struct uses pointers so that I can check for nil values

type user struct {
    Id      *string    `bson:"id" json:"id"`
    Name    *string    `bson:"name" json:"name"`
    ...
}

An update query that i've used elsewhere in my app looks like this:

err := collection("users").Update(bson.M{"id" : "user.Id"},bson.M{"$set": bson.M{"???":"???"}})

but I'm not sure how to construct the latter part of the query under these circumstances.

Note: I'm not using MongoDB's _id

答案1

得分: 0

我相信你只需要这样就能完成:

err := collection("users").Update(bson.M{"id": user.Id}, bson.M{"$set": &user})
英文:

I believe you should be able to accomplish this with just

err := collection("users").Update(bson.M{"id" : user.Id},bson.M{"$set": &user})

huangapple
  • 本文由 发表于 2015年9月10日 00:19:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/32484676.html
匿名

发表评论

匿名网友

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

确定