usersmodelgen.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Code generated by goctl. DO NOT EDIT.
  2. // goctl 1.8.1
  3. package model
  4. import (
  5. "context"
  6. "github.com/zeromicro/go-zero/core/stores/mon"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. )
  11. type usersModel interface {
  12. Insert(ctx context.Context, data *Users) error
  13. FindOne(ctx context.Context, id string) (*Users, error)
  14. FindOneByUsername(ctx context.Context, username string) (*Users, error)
  15. Update(ctx context.Context, data *Users) (*mongo.UpdateResult, error)
  16. Delete(ctx context.Context, id string) (int64, error)
  17. }
  18. type defaultUsersModel struct {
  19. conn *mon.Model
  20. }
  21. func newDefaultUsersModel(conn *mon.Model) *defaultUsersModel {
  22. return &defaultUsersModel{conn: conn}
  23. }
  24. func (m *defaultUsersModel) Insert(ctx context.Context, data *Users) error {
  25. if data.ID.IsZero() {
  26. data.ID = primitive.NewObjectID()
  27. }
  28. _, err := m.conn.InsertOne(ctx, data)
  29. return err
  30. }
  31. func (m *defaultUsersModel) FindOne(ctx context.Context, id string) (*Users, error) {
  32. oid, err := primitive.ObjectIDFromHex(id)
  33. if err != nil {
  34. return nil, ErrInvalidObjectId
  35. }
  36. var data Users
  37. err = m.conn.FindOne(ctx, &data, bson.M{"_id": oid})
  38. switch err {
  39. case nil:
  40. return &data, nil
  41. case mon.ErrNotFound:
  42. return nil, ErrNotFound
  43. default:
  44. return nil, err
  45. }
  46. }
  47. func (m *defaultUsersModel) FindOneByUsername(ctx context.Context, username string) (*Users, error) {
  48. var data Users
  49. err := m.conn.FindOne(ctx, &data, bson.M{"username": username})
  50. switch err {
  51. case nil:
  52. return &data, nil
  53. case mon.ErrNotFound:
  54. return nil, ErrNotFound
  55. default:
  56. return nil, err
  57. }
  58. }
  59. func (m *defaultUsersModel) Update(ctx context.Context, data *Users) (*mongo.UpdateResult, error) {
  60. res, err := m.conn.UpdateOne(ctx, bson.M{"_id": data.ID}, bson.M{"$set": data})
  61. return res, err
  62. }
  63. func (m *defaultUsersModel) Delete(ctx context.Context, id string) (int64, error) {
  64. oid, err := primitive.ObjectIDFromHex(id)
  65. if err != nil {
  66. return 0, ErrInvalidObjectId
  67. }
  68. res, err := m.conn.DeleteOne(ctx, bson.M{"_id": oid})
  69. return res, err
  70. }