我试图在MongoDB中通过Goland IDE插入数据。虽然连接是正确的,并且在集成开发环境的输出中我得到了ObjectID,但是我仍然不能直接从终端看到结果。数据库似乎记录了一个没有任何信息的新文档...
OSX,MongoDB是默认设置。驱动程序是'go.mongodb.org/mongo- Driver‘,连接正确。Goland在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)
这是插入部分,我按照mongodb.com上的指南进行了操作
> db.student.find()
{ "_id" : ObjectId("5d82d826f5e2f29823900275"), "name" : "Michael", "sex" : "Male" }
{ "_id" : ObjectId("5d82d845b8db68b150894f5a") }
{ "_id" : ObjectId("5d82dc2952c638d0970e9356") }
{ "_id" : ObjectId("5d82dcde8cf407b2fb5649e7") }
这是我在另一个终端上查询的结果。除了第一个有一些内容之外,其他三个是我通过Goland三次尝试插入到数据库中的内容。
发布于 2019-09-19 16:02:27
所以你的结构看起来像这样:
type Student struct {
name string
sex string
}
name
和sex
字段不以大写开头,因此它们不会导出,因此对反射是不可见的。InsertOne
无疑使用反射来确定newStu
中的内容,但是Student
结构没有导出字段,因此InsertOne
根本看不到newStu
中的任何字段。
如果您将结构修复为具有导出的字段:
type Student struct {
Name string
Sex string
}
然后InsertOne
就能弄清楚里面是什么了。MongoDB接口应该自己找出从Name
(Go)到name
(MongoDB)和Sex
到sex
的映射。
https://stackoverflow.com/questions/58002802
复制相似问题