伙計們,我正在嘗試使用用戶電話查詢 MongoDB 和 golan 中的集合,獲取用戶的 id 并使用它來查詢另一個集合,但是當我嘗試使用該回傳 id 時,它給了我一個錯誤
cannot use userid (variable of type interface{}) as string value in argument to primitive.ObjectIDFromHex: need type assertion
我的代碼
var result bson.M
err := userdataCollection.FindOne(context.TODO(), bson.M{"phone":" 2347000000"}).Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
// This error means your query did not match any documents.
return
}
log.Fatal(err)
}
var userid = result["_id"]
fmt.Printf("var6 = %T\n", userid)
json.NewEncoder(w).Encode(result["_id"]) // this returns prints the user id
id,_ := primitive.ObjectIDFromHex(userid) // where I am having the error
uj5u.com熱心網友回復:
回傳的_id已經是 type primitive.ObjectID,所以使用簡單的 type 斷言(并且不需要呼叫primitive.ObjectIDFromHex()):
id := userid.(primitive.ObjectID)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520341.html
上一篇:在主包中添加模塊作為git子模塊
下一篇:k8s如何秘密更新特定值
