dongxiong4571
dongxiong4571
2019-09-19 02:12

为什么在终端模式下找不到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 dongxing2015 2年前

    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.

    点赞 评论 复制链接分享

相关推荐