E
E
Eugene2020-03-04 10:13:52
go
Eugene, 2020-03-04 10:13:52

How can I find out if a user has not yet been added to the database?

I am using the official mongodb library.
When registering a new user, you need to find out if the id has been registered before.
However, if there is no such id in the database? FindOne method returns an error

mongo: no documents in result


How to separate an error in the absence of a record from real errors?

u := &models.User{}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := r.store.db.FindOne(ctx, bson.M{"userID": id}).Decode(u); err != nil {
  return nil, err
}

return u, nil

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-03-04
@you_are_enot

if errors.Is(err, mongo.ErrNoDocuments) {
// документа нет
}

// если у вас Го до 1.13
if err == mongo.ErrNoDocuments {
// документа нет
}

https://github.com/mongodb/mongo-go-driver/blob/d7...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question