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("[%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 {
// This error means your query did not match any documents.
log.Println("No matched documents!")
return
}
panic(err)
}
finalBytes, _ := bson.Marshal(bsonString)
bson.Unmarshal(finalBytes, &jsonString)
fmt.Println(jsonString)
My data is:
{"_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>"}]}
CodePudding user response:
You are unmarshalling a document into a string. If you did error handling you would see the error:
// no error haldling
json.Unmarshal(finalBytes, &jsonString)
// with error handling
err = json.Unmarshal(finalBytes, &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("[%s] > request for url\n", req.RemoteAddr)
// set headers
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 {
// This error means your query did not match any documents.
log.Println("No matched documents!")
return
}
panic(err)
}
// marshal & unmarshall
finalBytes, _ := bson.Marshal(bsonString)
bson.Unmarshal(finalBytes, &dataObject)
fmt.Println(dataObject)