My structure
struct task {
Id *bson.ObjectId `json:"id" bson:"_id,omitempty"`
Text string `json:"text" bson:"text,omitempty"`
// other params
}
Get data from form
var task Task{}
task.Text = FORM.Text
and my function to find tasks
func FindOne(task Task) (Task, error) {
err := db.Session.DB("tasks").C(CollectionTask).Find(&task).One(&task)
if err != nil {
return task, err
}
return task, nil
}
From the search form I only get a line text
, without a fieldid
, in this case, _id -> nil and mgo (mongo) finds nothing not found
How do I modify the search function or structure of the data to carry out a correct search?
This is a working example based on your code. It first connects, then insert and finally find a specific string. As you see if you insert your documents correctly your search function works fine.
package main
import (
"fmt"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type task struct {
ID *bson.ObjectId `json:"id" bson:"_id,omitempty"`
Text string `json:"text" bson:"text,omitempty"`
// other params
}
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
log.Fatal(err)
}
c := session.DB("test").C("test")
err = c.Insert(task{
Text: "Hello",
})
if err != nil {
log.Fatal(err)
}
var result task
err = c.Find(task{
ID: nil,
Text: "Hello",
}).One(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
I checked the implementation of insert
and found that the behavior changed, did not account for this
`Status string` json: "status" `
fixed on the Status string 'json: "status" bson: "-"'
and everything worked properly