dongxiong4571 2019-09-19 02:12
浏览 86
已采纳

为什么在终端模式下找不到IDE插入的数据?

I was trying to insert data through Goland IDE in MongoDB. Though the connection is right and in the IDE output I got the ObjectID, I still cannot see the results from terminal directly. It seems that the database records a new document without any information...

OSX, MongoDB is at default setting. Driver is 'go.mongodb.org/mongo-driver' and the connection is right. Goland is at 2019.2.2

// go

type Student struct {
    name string
    sex string
}

newStu := Student{
    name: "Alice",
    sex: "Female",
}

collection := client.Database("mgo_1").Collection("student")

insertResult, err := collection.InsertOne(context.TODO(), newStu)

if err != nil {
   log.Fatal(err)
    }

fmt.Println(insertResult.InsertedID)

This is the insertion part, which I followed the guide on mongodb.com

> db.student.find()
{ "_id" : ObjectId("5d82d826f5e2f29823900275"), "name" : "Michael", "sex" : "Male" }
{ "_id" : ObjectId("5d82d845b8db68b150894f5a") }
{ "_id" : ObjectId("5d82dc2952c638d0970e9356") }
{ "_id" : ObjectId("5d82dcde8cf407b2fb5649e7") }

This is the result I query in another terminal. Except the first one which has some content, the other three are what I tried to insert to the database through Goland for three times.

  • 写回答

1条回答 默认 最新

  • dongxing2015 2019-09-19 08:02
    关注

    So your struct looks like this:

    type Student struct {
        name string
        sex string
    }
    

    The name and sex fields don't begin with capitals so they're not exported and thus not visible to reflection. InsertOne undoubtedly uses reflection to figure out what's in newStu but the Student struct has no exported fields so InsertOne can't see any fields in newStu at all.

    If you fix your struct to have exported fields:

    type Student struct {
        Name string
        Sex string
    }
    

    then InsertOne will be able to figure out what's in it. The MongoDB interface should figure out the mapping from Name (Go) to name (MongoDB) and Sex to sex on its own.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记