在Golang中使用MongoDB驱动程序时,FindOne()始终返回空白。

huangapple go评论105阅读模式
英文:

Findone() always return blank with mongodb driver in golang

问题

我正在尝试使用Golang的MongoDB驱动程序搜索文档,但结果始终为空。

这是我的代码:

  1. var bsonString bson.M
  2. var jsonString string
  3. fmt.Printf("[%s] > request for url\n", req.RemoteAddr)
  4. w.Header().Set("Access-Control-Allow-Origin", "*")
  5. dataSource := client.Database(dbName)
  6. collection := dataSource.Collection(collectionName)
  7. err := collection.FindOne(context.Background(), bson.D{{"question.title", "Question"}}).Decode(&bsonString)
  8. if err != nil {
  9. if err == mongo.ErrNoDocuments {
  10. // 这个错误意味着你的查询没有匹配到任何文档。
  11. log.Println("No matched documents!")
  12. return
  13. }
  14. panic(err)
  15. }
  16. finalBytes, _ := bson.Marshal(bsonString)
  17. bson.Unmarshal(finalBytes, &jsonString)
  18. fmt.Println(jsonString)

我的数据是:

  1. {"_id":{"$oid":"631c5c78e606582e2ad78e2d"},"question":{"title":"Question","create_by":"AZ","time":{"$numberLong":"1661394765044"},"detail":"<h4>info</h4>"},"answers":[{"create_by":"baa","time":{"$numberLong":"1661394765044"},"detail":"<h4>abc</h4>"}]}
英文:

I'm trying to search a document in golang using mongodb driver. But the result is always blank.

This is my code:

  1. var bsonString bson.M
  2. var jsonString string
  3. fmt.Printf(&quot;[%s] &gt; request for url\n&quot;, req.RemoteAddr)
  4. w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
  5. dataSource := client.Database(dbName)
  6. collection := dataSource.Collection(collectionName)
  7. err := collection.FindOne(context.Background(), bson.D{{&quot;question.title&quot;, &quot;Question&quot;}}).Decode(&amp;bsonString)
  8. if err != nil {
  9. if err == mongo.ErrNoDocuments {
  10. // This error means your query did not match any documents.
  11. log.Println(&quot;No matched documents!&quot;)
  12. return
  13. }
  14. panic(err)
  15. }
  16. finalBytes, _ := bson.Marshal(bsonString)
  17. bson.Unmarshal(finalBytes, &amp;jsonString)
  18. fmt.Println(jsonString)

My data is:

  1. {&quot;_id&quot;:{&quot;$oid&quot;:&quot;631c5c78e606582e2ad78e2d&quot;},&quot;question&quot;:{&quot;title&quot;:&quot;Question&quot;,&quot;create_by&quot;:&quot;AZ&quot;,&quot;time&quot;:{&quot;$numberLong&quot;:&quot;1661394765044&quot;},&quot;detail&quot;:&quot;&lt;h4&gt;info&lt;/h4&gt;&quot;},&quot;answers&quot;:[{&quot;create_by&quot;:&quot;baa&quot;,&quot;time&quot;:{&quot;$numberLong&quot;:&quot;1661394765044&quot;},&quot;detail&quot;:&quot;&lt;h4&gt;abc&lt;/h4&gt;&quot;}]}

答案1

得分: 0

你正在将一个文档解组成一个字符串。如果你进行错误处理,你会看到错误信息:

  1. // 没有错误处理
  2. json.Unmarshal(finalBytes, &jsonString)
  3. // 带有错误处理
  4. err = json.Unmarshal(finalBytes, &jsonString)
  5. if err != nil {
  6. fmt.Println(err)
  7. // 输出: json: 无法将对象解组为类型为 string 的 Go 值
  8. }

你可以创建一个与你的数据匹配的结构体,或者解组到接口中(用于非结构化数据)。

  1. // 声明变量
  2. var bsonString bson.M
  3. var jsonString string
  4. dataSource := client.Database(dbName)
  5. collection := dataSource.Collection(collectionName)
  6. //
  7. dataObject := map[string]interface{}{}
  8. fmt.Printf("[%s] > 请求 URL\n", req.RemoteAddr)
  9. // 设置头部信息
  10. w.Header().Set("Access-Control-Allow-Origin", "*")
  11. err := collection.FindOne(context.Background(), bson.D{{"question.title", "Question"}}).Decode(&bsonString)
  12. if err != nil {
  13. if err == mongo.ErrNoDocuments {
  14. // 这个错误意味着你的查询没有匹配到任何文档。
  15. log.Println("没有匹配的文档!")
  16. return
  17. }
  18. panic(err)
  19. }
  20. // 编组和解组
  21. finalBytes, _ := bson.Marshal(bsonString)
  22. bson.Unmarshal(finalBytes, &dataObject)
  23. fmt.Println(dataObject)
英文:

You are unmarshalling a document into a string. If you did error handling you would see the error:

  1. // no error haldling
  2. json.Unmarshal(finalBytes, &amp;jsonString)
  3. // with error handling
  4. err = json.Unmarshal(finalBytes, &amp;jsonString)
  5. if err != nil {
  6. fmt.Println(err)
  7. // prints: json: cannot unmarshal object into Go value of type string
  8. }

You can create a struct to match your data or unmarshal into interface (for unstructured data).

  1. // declare variables
  2. var bsonString bson.M
  3. var jsonString string
  4. dataSource := client.Database(dbName)
  5. collection := dataSource.Collection(collectionName)
  6. //
  7. dataObject := map[string]interface{}{}
  8. fmt.Printf(&quot;[%s] &gt; request for url\n&quot;, req.RemoteAddr)
  9. // set headers
  10. w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
  11. err := collection.FindOne(context.Background(), bson.D{{&quot;question.title&quot;, &quot;Question&quot;}}).Decode(&amp;bsonString)
  12. if err != nil {
  13. if err == mongo.ErrNoDocuments {
  14. // This error means your query did not match any documents.
  15. log.Println(&quot;No matched documents!&quot;)
  16. return
  17. }
  18. panic(err)
  19. }
  20. // marshal &amp; unmarshall
  21. finalBytes, _ := bson.Marshal(bsonString)
  22. bson.Unmarshal(finalBytes, &amp;dataObject)
  23. fmt.Println(dataObject)

huangapple
  • 本文由 发表于 2022年9月11日 10:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/73676379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定