【发布时间】:2019-11-01 18:48:41
【问题描述】:
我尝试使用官方的 mongodb 驱动程序 (go.mongodb.org/mongo-driver) 从 Go 应用程序读取、写入和删除数据。
这是我要使用的结构:
Contact struct {
ID xid.ID `json:"contact_id" bson:"contact_id"`
SurName string `json:"surname" bson:"surname"`
PreName string `json:"prename" bson:"prename"`
}
// xid is https://github.com/rs/xid
我省略了添加到集合中的代码,因为这是查找。
我可以使用以下代码(缩写)获取具有特定contact_id的联系人列表:
filter := bson.D{}
cursor, err := contactCollection.Find(nil, filter)
for cur.Next(context.TODO()) {
...
}
这有效并返回文档。我想过对删除或匹配的获取做同样的事情:
// delete - abbreviated
filter := bson.M{"contact_id": id}
result, _ := contactCollection.DeleteMany(nil, filter)
// result.DeletedCount is always 0, err is nil
if err != nil {
sendError(c, err) // helper function
return
}
c.JSON(200, gin.H{
"ok": true,
"message": fmt.Sprintf("deleted %d patients", result.DeletedCount),
}) // will be called, it is part of a webservice done with gin
// get complete
func Get(c *gin.Context) {
defer c.Done()
id := c.Param("id")
filter := bson.M{"contact_id": id}
cur, err := contactCollection.Find(nil, filter)
if err != nil {
sendError(c, err) // helper function
return
} // no error
contacts := make([]types.Contact, 0)
for cur.Next(context.TODO()) { // nothing returned
// create a value into which the single document can be decoded
var elem types.Contact
err := cur.Decode(&elem)
if err != nil {
sendError(c, err) // helper function
return
}
contacts = append(contacts, elem)
}
c.JSON(200, contacts)
}
为什么同一个过滤器对删除不起作用?
编辑:插入代码如下:
_, _ = contactCollection.InsertOne(context.TODO(), Contact{
ID: "abcdefg",
SurName: "Demo",
PreName: "on stackoverflow",
})
【问题讨论】:
-
什么是
xid.ID?您可以发布类型声明及其方法吗?还有,DeleteMany()返回错误,不要省略,错误是什么?可能是您无权删除文档... -
我省略了错误,因为它没有返回错误
-
另外你必须使用
bson标签,而不是json。请在Contact结构中将json更改为bson,或者如果您也使用JSON,也请添加bson。 -
@icza 更新了更多代码
-
看起来你用字符串
id和Find(),和DeleteMany()一样吗?另外,你试过bson标签吗?