使用Golang查询MongoDB集合,并将ID作为字符串返回。

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

query a collection in mongodb using golan and returning an id as string

问题

伙计们,请帮我翻译一下。我正在尝试使用用户的电话号码在 MongoDB 和 Golang 中查询一个集合,获取用户的 ID,并使用该 ID 查询另一个集合。但是,当我尝试使用返回的 ID 时,它给出了以下错误:

无法将 userid类型为 interface{} 的变量作为字符串值传递给 primitive.ObjectIDFromHex需要类型断言

我的代码如下:

var result bson.M
err := userdataCollection.FindOne(context.TODO(), bson.M{"phone":"+2347000000"}).Decode(&result)
if err != nil {
    if err == mongo.ErrNoDocuments {
        // 这个错误意味着你的查询没有匹配到任何文档。
        return
    }
    log.Fatal(err)
}
var userid = result["_id"]
fmt.Printf("var6 = %T\n", userid)

json.NewEncoder(w).Encode(result["_id"]) // 这会打印用户的 ID

id,_ :=  primitive.ObjectIDFromHex(userid) // 这里出现了错误
英文:

Guys please i'm trying to query a collection in MongoDB and golan using the user phone, get the id of the user and use it to query another collection but when I try to use that return id it gives me an error of

cannot use userid (variable of type interface{}) as string value in argument to primitive.ObjectIDFromHex: need type assertion

My Code

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

答案1

得分: 1

返回的_id已经是primitive.ObjectID类型,所以可以使用简单的类型断言(无需调用primitive.ObjectIDFromHex()):

id := userid.(primitive.ObjectID)
英文:

The _id returned is already of type primitive.ObjectID, so use a simply type assertion (and no need to call primitive.ObjectIDFromHex()):

id := userid.(primitive.ObjectID)

huangapple
  • 本文由 发表于 2022年10月24日 02:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/74173697.html
匿名

发表评论

匿名网友

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

确定