dtwzwmv87399 2018-05-08 09:37
浏览 90
已采纳

将切片结果JSON插入MongoDB

I'm using the mgo driver for MongoDB, with the Gin framework.

type  Users struct {
    User_id *string  `json:"id user" bson:"id user"`
    Images  []string `json:"images" bson:"images"`
}

I have this function which tries to convert the slice into JSON.

The slice here is UsersTotal

func GetUsersApi(c *gin.Context) {

    UsersTotal, err := GetUsers()

    if err != nil {
        fmt.Println("error:", err)
    }

    c.JSON(http.StatusOK, gin.H{
        "Count Users": len(UsersTotal),
        "Users Found ": UsersTotal,
    })


    session, err := mgo.Dial(URL)
    if err == nil {
        fmt.Println("Connection to mongodb established ok!!")
        cc := session.DB("UsersDB").C("results")

        err22 := cc.Insert(&UsersTotal)
        if err22 != nil {
            fmt.Println("error insertion ", err22)
        }
    }
    session.Close()
   }

Running it I get the following error:

error insertion Wrong type for documents[0]. Expected a object, got a array.

  • 写回答

1条回答 默认 最新

  • douwan2664 2018-05-08 10:36
    关注

    Inserting multiple documents is the same as inserting a single one because the Collection.Insert() method has a variadic parameter:

    func (c *Collection) Insert(docs ...interface{}) error
    

    One thing you should note is that it expects interface{} values. Value of any type qualifies "to be" an interface{}. Another thing you should note is that only the slice type []interface{} qualifies to be []interface{}, a user slice []User does not. For details, see Type converting slices of interfaces in go

    So simply create a copy of your users slice where the copy has a type of []interface{}, and that you can directly pass to Collection.Insert():

    docs := make([]interface{}, len(UsersTotal))
    for i, u := range UsersTotal {
        docs[i] = u
    }
    
    err := cc.Insert(docs...)
    // Handle error
    

    Also please do not connect to MongodB in your handler. Do it once, on app startup, store the global connection / session, and clone / copy it when needed. For details see mgo - query performance seems consistently slow (500-650ms); and too many open files in mgo go server.

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

报告相同问题?

悬赏问题

  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中