php Editor Xigua will take you through this article to learn how to use Postgres and MongoDB for CRUD operations. Postgres is a relational database, while MongoDB is a document database. CRUD operations refer to the process of creating (Create), reading (Read), updating (Update) and deleting (Delete) data. By combining these two different types of databases, you can choose the most suitable database for data operations based on different needs to improve efficiency and flexibility. Next, let us explore the application of these two databases in CRUD operations!
Question content
I am fairly new to Go and backends, and am participating in the Go internship program. We built a CRUD that connects to a psql database and now I'm told to connect to mongoDB, which we will use for development and PSQL will be used for production. Do I have to create a new handler for mongo from scratch or can I use the same handler and somehow determine the type of database being used and use the logic accordingly? For example, I have a handler for the user registration endpoint:
func (ctrl *UserController) Register(c *gin.Context) { var user models.User if err := c.BindJSON(&user); err != nil { c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{ "error": true, "message": err.Error(), }) return } err := ctrl.userService.Register(&user) if err != nil { c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{ "error": true, "message": err.Error(), }) return } c.JSON(http.StatusCreated, gin.H{ "message": "successfully created an user", }) } func (svc *UserService) Register(user *models.User) error { if svc.userRepo.CheckIfEmailExists(user.Email) { return errors.New("user already registered") } hash, err := svc.generatePasswordHash(user.Password) if err != nil { return errors.New("err can't register user") } user.Password = hash return svc.userRepo.Insert(user) } func (repo *UserRepository) CheckIfEmailExists(mail string) bool { var user models.User err := repo.dbClient.Debug().Model(models.User{}).Where("email = ?", mail).Find(&user).Error return errors.Is(err, gorm.ErrRecordNotFound) } func (repo *UserRepository) Insert(user *models.User) error { err := repo.dbClient.Debug().Model(models.User{}).Create(user).Error if err != nil { log.Printf("failed to insert user: %v\n", err) return err } return nil }
I built the insert, register and CheckIfEmailExists functions for mongo:
func (repo *UserRepository) InsertInMongo(user *models.UserB) error { coll := repo.mongoClient.DB.Collection("users") _, err := coll.InsertOne(context.TODO(), user) if err != nil { log.Printf("failed to insert user: %v\n", err) return err } return nil } func (svc *UserService) RegisterToMongo(user *models.UserB) error { check := svc.userRepo.CheckIfEmailExistsInMongo(user.Email) if check { return errors.New("user already registered") } hash, err := svc.generatePasswordHash(user.Password) if err != nil { return errors.New("err can't register user") } user.Password = hash return svc.userRepo.InsertInMongo(user) } func (repo *UserRepository) CheckIfEmailExistsInMongo(email string) bool { coll := repo.mongoClient.Collection filter := bson.D{{Key: "email", Value: email}} count, err := coll.CountDocuments(context.TODO(), filter) if err != nil { panic(err) } if count != 0 { return true } return false }
Solution
You did not provide code on how to create UserService.
Ideally, you should have an interface that looks like this:
type UserRepository interface { CheckIfEmailExists(mail string) bool Insert(user *models.User) error … }
Then, the UserService should be created like this:
// We use the interface as param func NewUserService(userRepo UserRepository) UserService { return UserService{ UserRepo: userRepo } }
And you will have two separate repositories, both implementing the UserRepository
interface - this means they should have methods with the same name and same signature (parameters, return type) as the interface:
mongo_user_repository.go
Type MongoUserRepo struct { … } func (repo MongoUserRepo) CheckIfEmailExists(mail string) bool { … some mongo logic here } func (repo MongoUserRepo) Insert(user *models.User) error { … some mongo logic here }
postgres_user_repository.go
type PostgresUserRepo struct { … } func (repo PostgresUserRepo) CheckIfEmailExists(mail string) bool { … some postgres logic here } func (repo PostgresUserRepo) Insert(user *models.User) error { … some postgres logic here }
You can pass any of these depending on the use case, as in the (very bad) example below:
main.go
… var userService UserService if os.Getenv(“environment”) == “prod” { userService = NewUserService(postgreUserRepo) } else if os.Getenv(“environment”) == “dev” { userService = NewUserService(mongoUserRepo) }
The above is the detailed content of CRUD with Postgres and MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

如何在PHP中实现用户注册时发送短信验证码随着移动互联网的普及,手机号码已经成为用户注册和登录的重要凭证之一。为了保证用户账号的安全性,很多网站和应用都会在用户注册时发送短信验证码进行验证。本文将介绍如何在PHP中实现用户注册时发送短信验证码的功能,并附上具体的代码示例。一、创建短信验证码发送接口首先,我们需要创建一个短信验证码发送接口,用于向用户的手机号码

如何使用PHP和CGI实现用户注册和登录功能用户注册和登录是许多网站必备的功能之一。在本文中,我们将介绍如何使用PHP和CGI来实现这两个功能。我们将通过代码示例来演示整个过程。一、用户注册功能的实现用户注册功能允许新用户创建一个账户,并将其信息保存到数据库中。以下是实现用户注册功能的代码示例:创建数据库表首先,我们需要创建一个数据库表,用于存储用户信息。可

如何用PHP实现CMS系统的用户注册/登录功能?随着互联网的发展,CMS(ContentManagementSystem,内容管理系统)系统成为了网站开发中非常重要的一环。而其中的用户注册/登录功能更是不可或缺的一部分。本文将介绍如何使用PHP语言实现CMS系统的用户注册/登录功能,并附上相应的代码示例。以下是实现步骤:创建用户数据库首先,我们需要建立一

芝麻交易所是我国领先的在线交易平台之一,为各类商品提供安全、高效的交易服务。它的交易流程包括用户注册、商品展示、订单生成、交易撮合、物流配送以及售后服务等多个环节。本文将详细介绍芝麻交易所的交易流程,帮助读者更好地了解和使用该平台。用户注册与登录在使用芝麻交易所进行交易之前,用户必须注册并登录。用户可以选择通过手机验证码、第三方账号或手动注册的方式登录。在注册过程中,用户需要提供真实有效的个人信息,并同意遵守芝麻交易所的交易规则和用户协议。商品展示与搜索注册成功后,用户可进入芝麻交易所主页,通过

如何利用PHP函数实现用户注册和登录的验证码生成和验证?在网站的用户注册和登录页面中,为了防止机器人批量注册和攻击,通常需要添加验证码功能。本文将介绍如何利用PHP函数实现用户注册和登录的验证码生成和验证。验证码生成首先,我们需要生成随机的验证码图片供用户填写。PHP提供了GD库和图像处理函数,可以方便地生成验证码图片。<?php//创建一个画布

使用Laravel框架实现用户注册和登录功能的步骤Laravel是一个流行的PHP开发框架,提供了许多强大的功能和工具,使得开发者可以轻松构建各种Web应用程序。用户注册和登录是任何应用程序的基本功能之一,下面我们将使用Laravel框架来实现这两个功能。步骤1:创建新的Laravel项目首先,我们需要在本地计算机上创建一个新的Laravel项目。打开终端或

如何利用PHP实现用户注册功能在现代的网络应用程序中,用户注册功能是一个非常常见的需求。通过注册功能,用户可以创建自己的账户并使用相应的功能。本文将通过PHP编程语言来实现用户注册功能,并提供详细的代码示例。首先,我们需要创建一个HTML表单,用于接收用户的注册信息。在表单中,我们需要包含一些输入字段,如用户名、密码、邮箱等。可以根据实际需求自定义表单字段。

Node.js开发:如何实现用户注册和登录功能,需要具体代码示例引言:在Web应用程序开发过程中,用户注册和登录功能是必不可少的一部分。本文将详细介绍如何使用Node.js实现用户注册和登录功能,提供具体的代码示例。一、用户注册功能的实现创建数据库首先,我们需要创建一个数据库来存储用户的注册信息。可以使用MongoDB、MySQL等数据库来存储用户信息。创建


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
