GoLang mgo - mgo.ErrNotFound for find(...).All(...)
Asked Answered
S

1

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?

Shetler answered 1/6, 2017 at 8:51 Comment(0)
P
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().

Poplin answered 1/6, 2017 at 9:2 Comment(3)
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 1Shetler
@Shetler 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).Poplin
oh sorry, yes, you re right, there is something weitd with my selectQueryShetler

© 2022 - 2024 — McMap. All rights reserved.