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

Time:10-24

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

CodePudding user response:

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)
  • Related