5

I have a GoLang code:

c.Find(selectQuery).All(&results)
if err == mgo.ErrNotFound {
// error handling
}

selectQuery value is not important here.

I never get error ErrNotFound. Even if the query doesn't match any results I don't get ErrNotFound. I get variable result with empty attributes. How should I change the code to handle ErrNotFound case?

icza
  • 389,944
  • 63
  • 907
  • 827
poulius
  • 53
  • 1
  • 6

1 Answers1

8

Query.All() never returns mgo.ErrNotFound, so it's useless to check for that. If there are no results, the length of results will be 0, so that's how you can detect that if there were no errors:

err := c.Find(selectQuery).All(&results)
if err != nil { {
    // error handling
    return
}
// If you must detect "not found" case:
if len(results) == 0 {
    // No results
}

mgo.ErrNotFound is used / returned by other methods, usually by those which ought to operate on a single document, such as Query.One() or Query.Apply().

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you for the answer. The interesting thing is that I never get 0 for len(results). If my query doesn't match any results I get: [{Email: Name:}] As a result my len(results) is equal to 1 – poulius Jun 01 '17 at 10:01
  • 1
    @poulius Then likely you **do** have one result document, which has empty string as its `Email` and `Name` (or simply those fields are missing or incorrectly mapped). – icza Jun 01 '17 at 10:05
  • oh sorry, yes, you re right, there is something weitd with my selectQuery – poulius Jun 01 '17 at 10:18