I am totally Rookie , i am loking for a solution

Hi please look in this code Find_User in db_service.go
that i written for user login function and query user email and password but instade of returning some result it throwing blank result .
take a look. i am using mux and mongodb

func Find_User(user *model.User) (*mongo.ListDatabasesResult, error) {
	//Create a handle to the respective collection in the database.
	obejctId, err := primitive.ObjectIDFromHex(user.Email)
	if err != nil {
		return nil, err
	}
	result := clientInstance.Database(AUTH_DB).Collection(USER_COLLECTION).FindOne(context.Background(), bson.M{"_id": obejctId})

	result.Decode(&user)
	return nil, nil

}

here is the total code seperated in section
db_service.go

/* Used to create a singleton object of MongoDB client.
Initialized and exposed through  GetMongoClient().*/
var clientInstance *mongo.Client

//Used during creation of singleton client object in GetMongoClient().
var clientInstanceError error

//Used to execute client creation procedure only once.
var mongoOnce sync.Once

//I have used below constants just to hold required database config's.
const (
	CONNECTIONSTRING = "http://127.0.0.1:27017"
	AUTH_DB          = "Cluster0"
	USER_COLLECTION  = "user"
)

//GetMongoClient - Return mongodb connection to work with
func GetMongoClient() (*mongo.Client, error) {

	//Perform connection creation operation only once.
	mongoOnce.Do(func() {
		// Set client options
		clientOptions := options.Client().ApplyURI(CONNECTIONSTRING)
		// Connect to MongoDB
		client, err := mongo.Connect(context.TODO(), clientOptions)
		if err != nil {
			clientInstanceError = err
		}
		// Check the connection
		err = client.Ping(context.TODO(), nil)
		if err != nil {
			clientInstanceError = err
		}
		log.Println("Connected Mongodb!")
		clientInstance = client
	})

	return clientInstance, clientInstanceError
}

//CreateIssue - Insert a new document in the collection.
func User_Collection(user *model.User) (*mongo.InsertOneResult, error) {

	//Create a handle to the respective collection in the database.
	collection := clientInstance.Database(AUTH_DB).Collection(USER_COLLECTION)

	//Perform InsertOne operation & validate against the error.
	return collection.InsertOne(context.TODO(), user)
}
func Find_User(user *model.User) (*mongo.ListDatabasesResult, error) {
	//Create a handle to the respective collection in the database.
	obejctId, err := primitive.ObjectIDFromHex(user.Email)
	if err != nil {
		return nil, err
	}
	result := clientInstance.Database(AUTH_DB).Collection(USER_COLLECTION).FindOne(context.Background(), bson.M{"_id": obejctId})

	result.Decode(&user)
	return nil, nil

}

login_service.go

func Register_User(user *model.User) (interface{}, error) {

	user.CreatedAt = time.Now().UTC()
	user.UpdatedAt = time.Now().UTC()
	if result, err := util.User_Collection(user); err == nil {
		return result.InsertedID, err
	} else {
		return nil, err
	}
}

func Login_User(user *model.User) (interface{}, error) {

	if result, err := util.Find_User(user); err == nil {
		return result, err
	} else {
		return nil, err
	}
}

login.go

func Register(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	var user model.User
	if err := json.NewDecoder(r.Body).Decode(&user); err == nil {

		if _, err := service.Register_User(&user); err == nil {
			w.WriteHeader(http.StatusCreated)
			json.NewEncoder(w).Encode(user)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(err)
		}

	} else {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

}
func Login(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var user model.User
	if err := json.NewDecoder(r.Body).Decode(&user); err == nil {
		if _, err := service.Login_User(&user); err == nil {
			json.NewEncoder(w).Encode(user)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(err)
		}
	} else {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
}

please help me

Hi @Rajrup_Das,

Find_User() apparently returns nothing on success but updates the user parameter instead.

result.Decode(&user)
return nil, nil

That’s quite unusual, but anyway…

My first question would be, what does “throwing a blank result” exactly mean?

  • is user empty?
  • if so, does result contain the data you’d expect?
  • and does result.Decode() return an error that you can check?

Maybe you could add some code to dump the contents of result and user after they got filled, for example:

result := clientInstance.Database(AUTH_DB).Collection(USER_COLLECTION).FindOne(context.Background(), bson.M{"_id": obejctId})
log.Printf("%v\n", result)
result.Decode(&user)
log.Printf("%v\n", user)

And I hope it is ok if I comment on two things I noticed:

  • If you do not intend to use a return value, simply omit it. return nil, nil looks quite unusual.
  • By convention, names in Go should not contain underscores.
  • Tip: reduce the amount of indented code by removing the else branch in cases where the last statement in the function is a return anyway, for example:
    if err != nil {
        return err 
    }
    return nil
    
    The more the code is aligned to the left, the easier it is to read.
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.