无法使用Go检索MongoDB的查询输出。

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

Unable to retrieve query output of MongoDB using Go

问题

我正在使用Go和Gin。通常情况下,我会从代码中连接到本地的MongoDB实例。然而问题是,我调用FindOne来检查数据库中是否存在一个电子邮件。但是它没有返回任何数据。

数据库文件的内容如下:

package database

import (
	"fmt"
	"log"
	"time"
	"os"
	"context"

	"github.com/joho/godotenv"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"bootcamp.com/server/configs"
)

func DBinstance() *mongo.Client {
	err := godotenv.Load(".env.dev")
	if err != nil {
		log.Fatal("Mongo ENV Load status >>>>> ", configs.ENV_LOAD_ERROR)
	}

	MongoDb := os.Getenv("MONGODB_URL")

	client, err := mongo.NewClient(options.Client().ApplyURI(MongoDb))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(configs.DB_CONNECTED)
	return client
}

var Client *mongo.Client = DBinstance()

func OpenCollection(client *mongo.Client, collectionName string) *mongo.Collection {
	var collection *mongo.Collection = client.Database("dev-camper-go").Collection(collectionName)
	return collection
}

我将其用于服务中调用集合,代码如下:

var usersCollection *mongo.Collection = database.OpenCollection(database.Client, "user")
var userModel models.Users

以下是调用数据库的方法:

func CheckIfUserExists(emailId string, ctx context.Context, cancel context.CancelFunc) error {
	userExists := usersCollection.FindOne(ctx, bson.M{"email": "billi@gmail.com"}).Decode(&userModel)
	fmt.Println("Data From Services >>>>> ", userExists)
	return userExists
}

但是它打印出:

Data From Services >>>>> mongo: no documents in result

但是我在数据库中硬编码了数据,所以它应该返回数据。我在这里添加了一张图片作为证据。

请问有人可以帮助我理解这个问题吗?因为我正在学习Go,对这些主题的理解还不够深入。

完整的代码在GitHub链接上:https://github.com/SohamRoyNoel/go-bootcamper-api

请帮助我解决这个问题。谢谢。

英文:

I'm using Go and Gin. Generally I'm connecting my local MongoDB instance from code. Yet the problem is I'm calling FindOne to check if an email exists in DB. Still it's not returning any data.

The Db file looks like this

package database

import(
	"fmt"
	"log"
	"time"
	"os"
	"context"

	"github.com/joho/godotenv"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"bootcamp.com/server/configs"
	)

func DBinstance() *mongo.Client{
	err := godotenv.Load(".env.dev")
	if err!=nil{
		log.Fatal("Mongo ENV Load status >>>> ", configs.ENV_LOAD_ERROR)
	}

	MongoDb := os.Getenv("MONGODB_URL")

	client, err:= mongo.NewClient(options.Client().ApplyURI(MongoDb))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(configs.DB_CONNECTED)
	return client
}

var Client *mongo.Client = DBinstance()

func OpenCollection(client *mongo.Client, collectionName string) *mongo.Collection{
	var collection *mongo.Collection = client.Database("dev-camper-go").Collection(collectionName)
	return collection
}

and I'm taking that in services to call collection. which looks something like this.

var usersCollection *mongo.Collection = database.OpenCollection(database.Client, "user")
var userModel models.Users

Below is the method to call DB,

func CheckIfUserExists(emailId string, ctx context.Context, cancel context.CancelFunc)  error {
	userExists := usersCollection.FindOne(ctx, bson.M{"email": "billi@gmail.com"}).Decode(&userModel)
	fmt.Println("Data From Services >>>>> ", userExists);
	return userExists
}

but it's printing

Data From Services >>>>>  mongo: no documents in result

But as I hard coded data to DB, this should return data. Just adding one image for this
无法使用Go检索MongoDB的查询输出。

Can anyone please help me to understand the issue. As i'm learning Go, I've less understanding of these topics.

Full code on GitHub link: https://github.com/SohamRoyNoel/go-bootcamper-api

Please help me to fix this. Thanks.

答案1

得分: 1

看起来是一个拼写错误。

- var usersCollection *mongo.Collection = database.OpenCollection(database.Client, "user")
+ usersCollection := database.OpenCollection(database.Client, "users")

注意:根据截图,集合的名称应该是users,而不是user


附注:当你遇到问题时,尝试将程序简化为最小的可复现代码。这将有助于找出问题所在。例如,我将程序简化为以下代码:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017/dev-camper-go"))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	collection := client.Database("dev-camper-go").Collection("user")
	var userModel struct {
		ID    primitive.ObjectID `bson:"_id"`
		EMAIL *string            `json:"email" validate:"required,max=100"`
	}
	userExists := collection.FindOne(ctx, bson.M{"email": "billi@gmail.com"}).Decode(&userModel)
	fmt.Println("Data From Services >>>>> ", userExists)
}

如果我能够使用这个简化的代码复现问题,那么很好,我已经将问题缩小到几行代码。如果我不能复现问题,我将逐渐添加代码,直到能够复现问题。

英文:

Looks like a typo.

- var usersCollection *mongo.Collection = database.OpenCollection(database.Client, "user")
+ usersCollection := database.OpenCollection(database.Client, "users")

Note: According to the screenshot, the name of the collection should be users, not user.


PS: when you encounter an issue, try to reduce your program to a minimal reproducer. It will make it easy to find out what's wrong. For example, I will reduce the program to this one:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017/dev-camper-go"))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	collection := client.Database("dev-camper-go").Collection("user")
	var userModel struct {
		ID    primitive.ObjectID `bson:"_id"`
		EMAIL *string            `json:"email" validate:"required,max=100"`
	}
	userExists := collection.FindOne(ctx, bson.M{"email": "billi@gmail.com"}).Decode(&userModel)
	fmt.Println("Data From Services >>>>> ", userExists)
}

If I can reproduce the issue with this one, good, I have narrowed down the issue to several lines. If I can not, I will add back codes a small piece by a small piece until I can reproduce the issue.

huangapple
  • 本文由 发表于 2023年4月15日 13:26:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76020506.html
匿名

发表评论

匿名网友

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

确定