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

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

Findone() always return blank with mongodb driver in golang

问题

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

这是我的代码:

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

我的数据是:

{"_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:

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

My data is:

{&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

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

// 没有错误处理
json.Unmarshal(finalBytes, &jsonString)

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

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

// 声明变量
var bsonString bson.M
var jsonString string
dataSource := client.Database(dbName)
collection := dataSource.Collection(collectionName)
//
dataObject := map[string]interface{}{}

fmt.Printf("[%s] > 请求 URL\n", req.RemoteAddr)

// 设置头部信息
w.Header().Set("Access-Control-Allow-Origin", "*")


err := collection.FindOne(context.Background(), bson.D{{"question.title", "Question"}}).Decode(&bsonString)
if err != nil {
    if err == mongo.ErrNoDocuments {
        // 这个错误意味着你的查询没有匹配到任何文档。
        log.Println("没有匹配的文档!")
        return
    }
    panic(err)
}

// 编组和解组
finalBytes, _ := bson.Marshal(bsonString)
bson.Unmarshal(finalBytes, &dataObject)
fmt.Println(dataObject)
英文:

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

// no error haldling
json.Unmarshal(finalBytes, &amp;jsonString)

// with error handling
err = json.Unmarshal(finalBytes, &amp;jsonString)
if err != nil {
    fmt.Println(err)
    // prints: json: cannot unmarshal object into Go value of type string
}

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

// declare variables
var bsonString bson.M
var jsonString string
dataSource := client.Database(dbName)
collection := dataSource.Collection(collectionName)
//
dataObject := map[string]interface{}{}

fmt.Printf(&quot;[%s] &gt; request for url\n&quot;, req.RemoteAddr)

// set headers
w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)


err := collection.FindOne(context.Background(), bson.D{{&quot;question.title&quot;, &quot;Question&quot;}}).Decode(&amp;bsonString)
if err != nil {
    if err == mongo.ErrNoDocuments {
        // This error means your query did not match any documents.
        log.Println(&quot;No matched documents!&quot;)
        return
    }
    panic(err)
}

// marshal &amp; unmarshall
finalBytes, _ := bson.Marshal(bsonString)
bson.Unmarshal(finalBytes, &amp;dataObject)
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:

确定