Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GoLang mgo - mgo.ErrNotFound for find(...).All(...)

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?

like image 444
poulius Avatar asked Jun 01 '17 08:06

poulius


1 Answers

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().

like image 149
icza Avatar answered Oct 25 '22 09:10

icza