dongnan1989 2014-05-10 15:55
浏览 102
已采纳

使用mgo进行部分更新

I have the following problem. I need to convert a structure to map[string]interface{} in order to perform an update in database (using mgo as driver for mongodb).

Update

For partially updating a document in mongoDB, the (optimal) solution is to convert to a map and delete the unwanted fields. For converting from struct to map please refer to my other post


Original Post

I receive the data from client side javascript and write in the my struct model. But I don't want to change/update some fields and thus I need to convert my structure to a map[string]interface{} to delete the unwanted fields.

Converting the structure to json and then to map it's not ok because the field types are not preserved. For example, let the followin structure be an Image model:

type Image struct {
    Name string `json:name`
    Views int `json:views,string`
    Owner string `json:owner`
}

So far so good, but when I receive informations from client(i.e. javascript) the views field is a string. If I convert to a map the json input given from client, then the views field remains a string and the internal representation of this value is changed in database. So next time I read this image from database, the Views field is zeroed (because of it's string representation from database).

Thus I write the json input from client in structure (for proper conversion of Views variable). But the owner value shouldn't change (the one form database). So I need to convert again the structure to a map[string]interface{} and process that map before making the update in database.

Using the json package for this it's not an option, because the string tag from Views field will convert from int to string (when converting to map).

So far I've tried the following function for converting structure to map, and I use reflection package and am a noob with using it. Don't quite understand well the package.

I would be grateful if you would come up with some ideas. Thanks.

  • 写回答

1条回答 默认 最新

  • douzhuang1900 2014-05-10 16:43
    关注

    The solution can be:
    1. client json -> struct -> xml -> map -> database
    2. Update partital with $set operator:

    collection.Update(bson.M{"_id": id}, bson.M{"$set": bson.M{"name": "new Name"}}
    

    Read more: http://docs.mongodb.org/manual/reference/operator/update/set/
    3. Load the document that is going to be updated and store it in a tmp variable. Parse the user input to another variable. Overwrite the values you need to preserve before updating.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度