MongoDbPersistence<T> class

Abstract persistence component that stores data in MongoDB using plain driver.

This is the most basic persistence component that is only able to store data items of any type. Specific CRUD operations over the data items must be implemented in child classes by accessing this.client or this.collection properties.

Configuration parameters

  • collection: (optional) MongoDB collection name
  • connection:
    • discovery_key: (optional) a key to retrieve the connection from connect.idiscovery.html IDiscovery]
    • host: host name or IP address
    • port: port number (default: 27017)
    • uri: resource URI or connection string with all parameters in it
  • credential:
    • store_key: (optional) a key to retrieve the credentials from auth.icredentialstore.html ICredentialStore]
    • username: (optional) user name
    • password: (optional) user password
  • options:
    • max_pool_size: (optional) maximum connection pool size (default: 2)
    • keep_alive: (optional) enable connection keep alive (default: true)
    • connect_timeout: (optional) connection timeout in milliseconds (default: 5000)
    • socket_timeout: (optional) socket timeout in milliseconds (default: 360000)
    • auto_reconnect: (optional) enable auto reconnection (default: true)
    • reconnect_interval: (optional) reconnection interval in milliseconds (default: 1000)
    • max_page_size: (optional) maximum page size (default: 100)
    • replica_set: (optional) name of replica set
    • ssl: (optional) enable SSL connection (default: false)
    • auth_source: (optional) authentication source
    • debug: (optional) enable debug output (default: false).

References

  • *:logger:*:*:1.0 (optional) ILogger components to pass log messages
  • *:discovery:*:*:1.0 (optional) IDiscovery services
  • *:credential-store:*:*:1.0 (optional) Credential stores to resolve credentials

Example

class MyMongoDbPersistence extends MongoDbPersistence<MyData> {

  MyMongoDbPersistence():base('mydata');

  Future<MyData> getByName(String? correlationId, String name) {
      var filter = {'name': name};
      var query = mngquery.SelectorBuilder();
      var selector = <String, dynamic>{};
      selector[r'$query'] = filter;
      query.raw(selector);
      var item = await collection.findOne(filter);
      if (item == null) {
        return null;
      }
      item = convertToPublic(item);
      var instance = MyData.fromJson(item);
      return instance;
  });

  Future<MyData> set(String correlatonId, MyData item) {
    if (item == null) {
      return null;
    }
    var jsonMap = json.decode(json.encode(item));
    // Assign unique id
    if (jsonMap['id'] == null) {
      jsonMap['id'] = IdGenerator.nextLong();
    }
    convertFromPublic(jsonMap);
    var filter = {r'$query': {'name': jsonMap['name']}};
    var result = await collection.findAndModify(
        query: filter, update: jsonMap, returnNew: true, upsert: true);
    if (result != null) {
        convertToPublic(result);
        var newItem = MyData.fromJson(result);;
        return newItem;
    }
    return null;
  }

}

var persistence = MyMongoDbPersistence();
persistence.configure(ConfigParams.fromTuples([
    'host', 'localhost',
    'port', 27017
]));

await persitence.open('123');

await persistence.set('123', { name: 'ABC' });
var item = await persistence.getByName('123', 'ABC');
print(item);         // Result: { name: 'ABC' }
Implementers

Constructors

MongoDbPersistence([String? collection])
Creates a new instance of the persistence component.

Properties

client ↔ Db?
The MongoDB connection object.
getter/setter pair
collection ↔ DbCollection?
The MongoDb database object. The MongoDb collection object.
getter/setter pair
collectionName String?
The MongoDB colleciton object.
getter/setter pair
connection MongoDbConnection?
The MongoDB connection component.
getter/setter pair
databaseName String?
The MongoDB database name.
getter/setter pair
dependencyResolver ↔ DependencyResolver
The dependency resolver.
getter/setter pair
hashCode int
The hash code for this object.
no setterinherited
logger ↔ CompositeLogger
The logger.
getter/setter pair
maxPageSize int
getter/setter pair
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

clear(String? correlationId) Future
Clears component state.
close(String? correlationId) Future
Closes component and frees used resources.
configure(ConfigParams config) → void
Configures component by passing configuration parameters.
convertFromPublic(dynamic item, {bool createUid = false}) Map<String, dynamic>?
Convert object value from public to internal format.
convertFromPublicPartial(Map<String, dynamic>? item) Map<String, dynamic>?
Converts the given object from the public partial format.
convertToPublic(Map<String, dynamic>? item) → dynamic
Converts object value from internal to public format.
create(String? correlationId, T? item) Future<T?>
Creates a data item.
deleteByFilterEx(String? correlationId, Map<String, dynamic> filter) Future
Deletes data items that match to a given filter.
ensureIndex(dynamic keys, {String key = '', bool unique = false, bool sparse = false, bool background = false, bool dropDups = false, Map<String, dynamic>? partialFilterExpression, String name = ''}) → void
Adds index definition to create it on opening
getCountByFilterEx(String? correlationId, Map<String, dynamic>? filter) Future<int>
Gets a count of data items retrieved by a given filter.
getListByFilterEx(String? correlationId, Map<String, dynamic>? filter, Map<String, dynamic>? sort) Future<List<T>>
Gets a list of data items retrieved by a given filter and sorted according to sort parameters.
getOneRandomEx(String? correlationId, Map<String, dynamic> filter) Future<T?>
Gets a random item from items that match to a given filter.
getPageByFilterEx(String? correlationId, Map<String, dynamic>? filter, PagingParams? paging, Map<String, dynamic>? sort) Future<DataPage<T>>
Gets a page of data items retrieved by a given filter and sorted according to sort parameters.
isOpen() bool
Checks if the component is opened.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
open(String? correlationId) Future
Opens the component.
setReferences(IReferences references) → void
Sets references to dependent components.
toString() String
A string representation of this object.
inherited
unsetReferences() → void
Unsets (clears) previously set references to dependent components.

Operators

operator ==(Object other) bool
The equality operator.
inherited