An Object/Document Mapping (ODM) framework for Node.js and MongodDB
Hydrate provides a means for developers to map Node.js classes to documents stored in a MongoDB database. Developers can work normally with objects and classes, and Hydrate takes care of the onerous details such as serializing classes to documents, validation, mapping of class inheritance, optimistic locking, fetching of references between database collections, change tracking, and managing of persistence through bulk operations.
Hydrate uses an approach to the persistence API similar to Hibernate ORM. Developers familiar with this approach should feel at home with Hydrate. Furthermore, Hydrate's query API is kept as similar as possible to the MongoDB native Node.js driver.
MongoDB bulk write operations are used to synchronize changes with the database, which can result in significant performance gains.
Breaking Changes in 2.0
Version 2.0 updates Hydrate to use version 3.0 of the MongoDB NodeJS native driver. Version 3.0 of the MongoDB NodeJS driver introduces several breaking changes which result in breaking changes in Hydrate.
- Since MongoClient.connect(...) now returns a MongoClient object instead of a Db object, createSessionFactory now takes a MongoClient object instead of a Db object.
- The new NodeJS MongoDB driver now requires that a database name be specified in order to get a Db object. Therefore, the database name must now be specified in Hydrate. There are 3 ways this can be done (in order of priority from highest to lowest): 1) Specify the database name in the @Collection decorator, 2) Provide the database name as an argument to createSessionFactory, or 3) Specify the database name in the Configuration.
- The connection property on the SessionFactory is now a MongoClient object instead of a Db object.
- The MongoDB driver was change to a peer dependency
- In version 2.2 of the MongoDB NodeJS native driver, domain support was disabled by default. You can enable with the domainsEnabled parameter on MongoClient. Domain support is not required for Hydrate, but you should be aware of this change when upgrading the MongoDB driver.
$ npm install hydrate-mongodb --save
Defining a Model
In this example we'll model a task list. We create a file,
model.ts, defining entities
Person. We also
define an enumeration used to indicate the status of a task on the task list.
Connecting to MongoDB
We use the standard MongoDB native driver to establish a connection to MongoDB. Once the connection is open, we create a SessionFactory using the MongoDB connection and the previously defined Configuration.
Creating a Session
A Hydrate Session should not be confused with the web-server session. The Hydrate Session is analogous to JPA's EntityManager, and is responsible for managing the lifecycle of persistent entities.
Typically the SessionFactory is created once at server startup and then used to create a Session for each connection to the server. For example, using a Session in an Express route might look something like this:
Working with Persistent Objects
To find a task by identifier we use find.
To find all tasks that have not yet been completed, we can use the query method.
Below is an example of finding all tasks assigned to a specific person. Note that even though
person is an instance
Person entity which is serialized as an
ObjectId in the
task collection, there is no need to pass the
identifier of the
person directly to the query.
For example, say we wanted to fetch the
Person that a
Task is assigned to.
The fetch method can be used in conjunction with queries as well.
Promises and Observables
Example: Finding an entity by identifier
Example: Finding entities by criteria
In TypeScript, the emitDecoratorMetadata and experimentalDecorators options must be enabled on the compiler.
Entities are classes that map to a document in a MongoDB collection.
- The entity must be a class
- The entity must be decorated with the Entity decorator
- The entity is not required to have a parameterless constructor, which is different than JPA and Hibernate. This allows for entities to enforce required parameters for construction. When an entity is deserialized from the database, the constructor is not called. This means the internal state of an entity must fully represented by it's serialized fields.
- An identifier is assigned to the entity when it is saved.
- If the Immutable decorator is specified on an Entity, the entity is excluded from dirty checking.
If a name for the collection is not given, an entity is mapped to a collection in MongoDB based on the name of the class. The collectionNamingStrategy in the Configuration is used to determine the name of the collection. The default naming strategy is CamelCase. Alternatively, a name for the collection can be specified using the Collection decorator.
Fields are mapped on an opt-in basis. Only fields that are decorated are mapped. The name for the field in the document can optionally be specified using the Field decorator.
The identityGenerator on the Configuration is used to generate an identifier for an entity. The default identity generator is the ObjectIdGenerator. This is the only generator that ships with Hydrate. Composite identifiers are not supported. Natural identifiers are not supported.
The identifier is exposed on an entity as a string through the
id property and in it's native format, typically ObjectID,
_id property. This is the default behavior and cannot be disabled. No decorator is required.
If you do not want to use one or more of the identity properties, you can leave them off your class definition.
Embeddables are classes that map to nested subdocuments within entities, arrays, or other embeddables.
- The embeddable must be a class
- The embeddable must be decorated with the Embeddable decorator
- Like an entity, an embeddable is not required to have a parameterless constructor. When an embeddable is deserialized from the database, the constructor is not called. This means the internal state of an embeddable must fully represented by it's serialized fields.
- If the Immutable decorator is specified on an Embeddable class, the original document for the Embeddable is cached and used for serialization.
Using the Parent decorator, Embeddables can designate a property to reference the object they are embedded in. The property is automatically populated with a reference to the parent object when the embeddable is loaded from the database. Properties annotated with Parent are not persisted to the database.
When using TypeScript, the type of a field is automatically provided. The following types are supported:
When a property is an embeddable or a reference to an entity, sometimes the type of the property cannot be determined
because of circular references of
import statements. In this case the
Type decorator should be used with the name
of the type.
TypeScript does not provide the type of an array element, so the type of the array element must be indicate with the ElementType decorator.
This is true for primitive types as well.
By default enums are serialized as numbers. Use the Enumerated decorator to serialize enums as strings.
Standard prototypical inheritance is supported for both entities and embeddables.
All entities within an inheritance hierarchy are stored in the same collection. If the Collection decorator is used, it is only valid on the root of an inheritance hierarchy.
Entities stored in separate collections may share a common superclass that is not mapped to a collection. In the example,
Patient (stored in
patient collection) and
Document (stored in
document collection) share a common
Asset that defines the field
Asset was decorated with Entity then
Document would instead both be stored in a collection called
If an inheritance hierarchy is defined, a discriminator field is added to the serialized document to indicate the type when deserializing the entity or embeddable. By default, the discriminatorField on the Configuration is used to determine the name of the field to store the discriminator. Optionally, the discriminator field can be specified on the root of an inheritance hierarchy using the DiscriminatorField decorator.
The class discriminator can be specified using the DiscriminatorValue decorator.
Eager Fetching of Entity References
By default entity references are not loaded and must be fetched using Session#fetch or similar. If a FetchType of Eager is specified on an entity reference then that reference is automatically fetched when the entity is loaded.
- This works on entity reference in Embeddable objects as well.
- It is generally preferable to fetch references as needed.
- A FetchType of Eager on a property that is not an entity reference has no effect.
Lazy Fetching of Properties
When an entity is loaded, all fields for that entity are retrieved from the database. Specifying a FetchType of Lazy for a field causes that field to not be retrieved from the database when the entity is loaded. The field is only loaded by calling Session#fetch and indicating which field to load.
- Useful for properties that contain large amounts of data, such as images, that are not always needed.
- A FetchType of Lazy on a property in an Embeddable objects is ignored. All properties in an embeddable object are always loaded from the database.
- It is generally not advisable to use a FetchType of Lazy on a property that is an entity reference.
Make sure you are defining appropriate indexes on the Entities and creating them in the database. To define indexes use the @Index decorator on an Entity. To create the indexes in the database call createIndexes on the SessionFactory or set createIndexes to true in the Configuration. You can do this on server start up when NODE_ENV does not equal "production". For production you can call createIndexes as needed as part of your deployment process.
The default ChangeTrackingType, DeferredImplicit, during a flush will dirty check, every Entity that is loaded in the Session. Although this is convenient, because you don't have to worry about when Entities are modified, the dirty checking is expensive. If you have entities that are frequently loaded and rarely modified, you should consider switching to DeferredExplicit change tracking. This will only dirty check entities when you explicitly call save on the Session. You can set change tracking on an entity using the @ChangeTracking decorator. You can switch to DeferredExplicit change tracking for all Entities instead by default by setting the changeTracking property on the Configuration.
If you know Entities will never change, set them as immutable using the @Immutable decorator. This will disable change tracking and optimistic locking for the entity. This means the Entity will never be dirty checked or written to the database after the first time it's written.
If you know your embedded classes will not change, set them to immutable as well using the @Immutable decorator. When an embedded class is immutable, it will be skipped when Hydrate is dirty checking the containing Entity and the embedded's document representation will be cached for serialization.
If you are pulling back large amounts of data in situations where no domain logic will be used and the entity will not be modified, such as for reports, consider querying the database directly. You can access the underlying database connection with the connection property of the SessionFactory. For example: session.factory.getCollection(User).aggregate(...)
Duplicate data to avoid fetching Entity references. For example, let's say you have a Book entity that references an Author entity, and you often have to fetch the Author of the Book just to display the name of the author. Instead, store the name of the Author as a property on the Book (in addition to the reference to the Author) so that you don't need to fetch the Author every time you load a Book. This also helps with reporting if you are using the database connection directly for reporting (as suggested above).
If you have a property on an Entity that stores large amounts of data, such as a binary file or photo, set it to lazy fetching with the @Fetch decorator. When a property is set to FetchType.Lazy, it is not loaded from the database when the Entity is loaded unless it is explicitly fetched using fetch on the Session.
Generally avoid using FetchType.Eager on entity references since it could end up loading a large portion of your entity graph. Instead, fetch entity references as needed.
To help identify slow queries during development, add a bunyan logger with a log level of TRACE as the logger property in the Configuration. This will log all queries executed along with the amount of time it took to execute the query. You can then execute slow queries directly in the MongoDB shell with explain to determine what indexes will be helpful (or if your current indexes are working as expected). Note that ObjectId's logged in the queries are printed as strings so you need to make sure to wrap them with ObjectId when running a query in the MongoDB shell.
The logger will also print out summary information for a flush, such as the execution time, and the number of entities inserted, updated, removed, and dirty checked. If your flushes are slow, consider using the strategies mentioned above to reduce dirty checking and serialization time.
It is not recommend using the logger in a production environment.