add existence-checking functionality to models

This commit is contained in:
☙◦ The Tablet ❀ GamerGirlandCo ◦❧ 2025-06-30 16:55:39 -04:00
parent f39e1b9c64
commit 4f6d75f9d8
Signed by: tablet
GPG Key ID: 924A5F6AF051E87C

View File

@ -40,6 +40,8 @@ type IModel interface {
FindByID(id interface{}) (*Query, error) FindByID(id interface{}) (*Query, error)
FindOne(query interface{}, options *options.FindOneOptionsBuilder) (*Query, error) FindOne(query interface{}, options *options.FindOneOptionsBuilder) (*Query, error)
FindPaged(query interface{}, page int64, perPage int64, options *options.FindOptionsBuilder) (*Query, error) FindPaged(query interface{}, page int64, perPage int64, options *options.FindOptionsBuilder) (*Query, error)
Exists(query interface{}) (bool, error)
ExistsID(id interface{}) (bool, error)
Collection() *mongo.Collection Collection() *mongo.Collection
getIdxs() []*mongo.IndexModel getIdxs() []*mongo.IndexModel
@ -199,6 +201,16 @@ func (m *Model) Count(query interface{}, options *options.CountOptionsBuilder) (
return coll.CountDocuments(context.TODO(), query, options) return coll.CountDocuments(context.TODO(), query, options)
} }
func (m *Model) Exists(query interface{}) (bool, error) {
cnt, err := m.Count(query, options.Count())
return cnt > 0, err
}
func (m *Model) ExistsID(id interface{}) (bool, error) {
cnt, err := m.Count(bson.M{"_id": id}, options.Count())
return cnt > 0, err
}
func createBase(d any) (reflect.Value, int, string) { func createBase(d any) (reflect.Value, int, string) {
var n string var n string
var ri *Model var ri *Model