Like/gte/lte queries with struct in GORM using postgres - postgresql

I have a User struct like this:
type User struct {
Username string `json:"username" bson:"username"`
AuthorizationKey string `json:"authorization_key" bson:"authorization_key"`
IsActive bool `json:"is_active" bson:"is_active"`
}
Right now I can query for the whole username using
user := &User{}
if err := db.Where(&User{
Username: username,
}).Find(&user).Error; err != nil {
return user, err
}
And I use this statement for like query (plain query)
db.Where("username LIKE ?", fmt.Sprintf("%%%s%%", username)).Find(&users)
Is it possible to use like query for username field with struct format? How about greater than or less than?

I think it's not possible, Struct in where condition used for equal check for field (Ref)
db.Where(&User{ Username: username})
For Like/gte/lte query you have to use plain SQL inside where()
db.Where("username LIKE ?", fmt.Sprintf("%%%s%%", username)).Find(&users)
Reference here

Related

GORM deleted_at" IS NULL

I just started learning GORM and currently trying to fetch data from one to many tables.
I have two tables :users and documents. A user can have multiple documents . When i try fetching documents I keep getting the error
documents: unsupported relations for schema User
SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL
Below is the code where I attempt to fetch data
type User struct {
gorm.Model
Name string
Email string
Password string
Documents []Document
}
type Document struct {
gorm.Model
Name string
DateCreated string
UserID uint
}
Function to fetch data
func GetAll(db *gorm.DB) ([]models.User, error) {
var users []models.User
// err := db.Model(&models.User{}).Preload("documents").Find(&users).Error
err:=db.Preload("documents").Find(&[]models.User{}).Error
fmt.Println(err)
fmt.Println("got users")
return users, err
}
What am I doing wrong here?
db.Preload("documents") should be db.Preload("Documents")
same as name of the field Documents in User struct

GORM nil error when fetching data from postgres

I'm trying to fetch one to many table data from my postgres DB using GORM but I keep getting the following error when I attempt to print the returned data
&{0xc00015e3f0 <nil> 1 0xc000272e00 0}
I have verified that the data exists in my db and here is the code showing how I've structured everything
type User struct {
gorm.Model
Name string
Email string
Password string
Documents []Document
}
type Document struct {
gorm.Model
Name string
DateCreated string
UserID uint
}
func GetAll(db *gorm.DB) ([]*models.User,) {
var users []*models.User
//err := db.Model(&models.User{}).Preload("Documents").Find(&users).Error
results:=db.Preload("Documents").Find(&users)
fmt.Println(results)
fmt.Println("got users")
return users
}
func main (){
models.Db.Create(&models.User{Name: "Ellie",Email: "Ellie#lous",
Documents: []models.Document{{Name:"Ellies ID",},{Name: "Ellies Guitar "}},
})
GetAll(models.Db)
}
Your error is that the data from your query will scan into users, not results.
Try this:
_ = db.Preload("Documents").Find(&users)
for _, user := range users {
fmt.Println(user)
}
The Find function returns a *gorm.DB object, not the results of your query.

Fail to decode mongo document ID onto struct field

Trying to use mongo go driver to decode a fetch a single user document and decode it into a struct, using the findOne method. But, I am unable to decode the document ID on the struct field. I tried looking for it in their examples, or at other sites/blogs, but no luck. I am working with:
go v1.13.4
mongo v4.2.1
mongo-go-driver v1.1.3
Below is the code snippet:
type User struct {
ID interface{} `json:"_id"`
Name string
Email string
Password string // hashed
}
/* Other versions of User struct which I already tried
type User struct {
ID interface{}
Name string
Email string
Password string // hashed
}
type User struct {
ID string `json:"_id"`
Name string
Email string
Password string // hashed
}
type User struct {
ID string
Name string
Email string
Password string // hashed
}
*/
func main() {
conn := service.MongoConn() // get a mongo connection on the required database
user := &service.User{}
err := conn.Collection("users").
FindOne(context.Background(), bson.M{"email": "foo#bar.com"}).
Decode(user)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", user)
}
I want to use doc ID as a reference in other documents in a different collection, otherwise, I have to resort to some other unique field like email.
the struct should be like this:
import "go.mongodb.org/mongo-driver/bson/primitive"
type User struct {
ID primitive.ObjectID `bson:"_id"`
...
}
to transfer your _id to string please use xx.ID.Hex()
see more on Github

Trying to pull data from mongodb using go [duplicate]

I'm trying to learn Go API development. I have a MongoDB instance running in a Docker container. I'm trying to follow a few guides but am failing on simple queries. I don't fully understand the use of BSON and JSON tags here. I do know what those terms mean. So here is my code.
import (
"fmt"
"time"
"gopkg.in/mgo.v2/bson"
)
const (
hosts = "localhost:27017"
database = "my_database"
username = "dev1"
password = "password123"
collection = "users"
)
type users struct {
user string `bson:"user" json:"user"`
data string
}
func main() {
fmt.Println("Starting Application!")
info := &mgo.DialInfo{
Addrs: []string{hosts},
Timeout: 60 * time.Second,
Database: database,
Username: username,
Password: password,
}
session, err1 := mgo.DialWithInfo(info)
if err1 != nil {
panic(err1)
}
defer session.Close()
col := session.DB(database).C(collection)
var user users
var books []users
var username = "cat"
col.Insert(&users{user: "dog", data: "blah"})
err3 := col.Find(bson.M{"user": username}).One(&user)
fmt.Println(user)
fmt.Println(err3)
count, err2 := col.Count()
if err2 != nil {
panic(err2)
}
fmt.Println(fmt.Sprintf("Messages count: %d", count))
fmt.Println(user)
col.Find(bson.M{}).All(&books)
fmt.Println(books)
}
Basically I'm getting empty objects on the print line but am getting the correct Message count. I inserted the objects with robomongo if that helps.
You must export fields of structs, else they are ignored by the mgo package. Change fields of users to User and Data.
type users struct {
User string `bson:"user" json:"user"`
Data string `bson:"data" json:"data"`
}
By default when a struct value is transformed / stored / retrieved from MongoDB, the field name is used. If you want to use different names, you may use tags to tell what names should the fields map to.

Golang mgo getting empty objects

I'm trying to learn Go API development. I have a MongoDB instance running in a Docker container. I'm trying to follow a few guides but am failing on simple queries. I don't fully understand the use of BSON and JSON tags here. I do know what those terms mean. So here is my code.
import (
"fmt"
"time"
"gopkg.in/mgo.v2/bson"
)
const (
hosts = "localhost:27017"
database = "my_database"
username = "dev1"
password = "password123"
collection = "users"
)
type users struct {
user string `bson:"user" json:"user"`
data string
}
func main() {
fmt.Println("Starting Application!")
info := &mgo.DialInfo{
Addrs: []string{hosts},
Timeout: 60 * time.Second,
Database: database,
Username: username,
Password: password,
}
session, err1 := mgo.DialWithInfo(info)
if err1 != nil {
panic(err1)
}
defer session.Close()
col := session.DB(database).C(collection)
var user users
var books []users
var username = "cat"
col.Insert(&users{user: "dog", data: "blah"})
err3 := col.Find(bson.M{"user": username}).One(&user)
fmt.Println(user)
fmt.Println(err3)
count, err2 := col.Count()
if err2 != nil {
panic(err2)
}
fmt.Println(fmt.Sprintf("Messages count: %d", count))
fmt.Println(user)
col.Find(bson.M{}).All(&books)
fmt.Println(books)
}
Basically I'm getting empty objects on the print line but am getting the correct Message count. I inserted the objects with robomongo if that helps.
You must export fields of structs, else they are ignored by the mgo package. Change fields of users to User and Data.
type users struct {
User string `bson:"user" json:"user"`
Data string `bson:"data" json:"data"`
}
By default when a struct value is transformed / stored / retrieved from MongoDB, the field name is used. If you want to use different names, you may use tags to tell what names should the fields map to.