go - mgo $inc 更新不起作用

标签 go mgo

我尝试在每次访问特定博客时更新浏览次数

type Blog struct {
    ID          bson.ObjectId `bson:"_id,omitempty"`
    Topic       string
    TimeCreated string
    Views       int
    Sections    []Section
}
type Section struct {
    Name    string
    Content string
}

和 Controller

func Blogs(w http.ResponseWriter, r *http.Request) {
    id := r.FormValue("id")
    if id != "" {
        blog := model.Blog{}
        colQuerier := bson.M{"_id": bson.ObjectIdHex(id)}

        e := mCollection.Find(colQuerier).One(&blog)
        if e != nil {
            console.PrintError(e)
            return
        }
        views := blog.Views
        fmt.Println(views)
        change := bson.M{"$inc": bson.M{"Views": 1}}

        e = mCollection.Update(colQuerier, change)
        if e != nil {
            console.PrintError(e)
        }

        jsonData, _ := json.Marshal(blog)
        fmt.Fprintf(w, string(jsonData))
     }
}

//console是一个内部包

代码获取内容但不增加 View

最佳答案

我找到了答案, 所以即使模型有“ View ”。在集合中它是“ View ”,因此它不断增加“ View ”,但它从未出现,因为 golang 正在寻找“ View ”。

所以工作代码是

change := bson.M{"$inc": bson.M{"views": 1}}

关于go - mgo $inc 更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533245/

相关文章:

javascript - 发送后如何在 OPEN 就绪状态下保持 websocket 连接?

go - 在DDD(纯净/六角形)架构中处理数据库连接和Env配置

go - 为什么当我通过反射构造它时,Golang yaml.v2 将我的结构转换为映射?

dictionary - 根据键数组和值构建任意深度的嵌套 map

go - 将不同的结构传递给函数(GO)?

mongodb - 使用golang mgo查询日期范围之间的mongodb日期

amazon-web-services - Cognito 自定义消息触发器没有任何效果

mongodb - 如何使用 golang 的 mgo 包进行类似查询

mongodb - 使用 Go 获取集合中所有键的名称

mongodb - 带有 mgo 的非结构化内部文档