Mongoose Facets
Facet injection for your Mongoose models. Read more about facets in MongoDB.
Installation
npm install mongoose-facets
Usage
The convention for naming facet models is FooFacet
. They should be defined
in files with the corresponding name and export the model returned by the
mongoose.model()
method. For example, in FooFacet.js
:
moduleexports = mongoose;
Place all the facets in the same directory as the parent model and plug in mongoose facets:
ParentSchema;
You can place them in a different directory if you choose; just specify the
correct directory in the dirname
option.
Each facet schema will be added to the parent schema under the key
facets.{name}
where the name is taken from the name of the model minus the
"Facet" suffix, i.e. FooFacet
will added be under the key facets.foo
.
A boolean flag of the form facetFlags.{name}
will also be added to the
parent schema for each facet. This value will be automagically set properly by
the plugin depending on whether a given facet object exists under the
appropriate key. You can use these flags to query by facet type:
Parent p1 = Parent;Parent p2 = Parent;// find parents with a foo facet and whose name starts with 'joe'const results = Parent;// only p1 is returnedassert;
The directory containing the facets can also include a file called
facet_indexes.js
which exports indexes that should be applied to the parent
collection. This should be an array of arrays where the sub-arrays are
arguments to the Schema.index()
method:
moduleexports = fieldA: 1 unique: true fieldB: 1 fieldC: -1;
You can export a function instead if you want to make this more dynamic. The
function will be passed all of the facet keys that have been discovered and
added to the parent schema (these will be relative keys minus the facets.
prefix, not the full absolute key):
// create an index by name for each facet, // i.e. to find "users with an admin facet and name that starts with ..."module { return facetKeys;};
The facet keys will also be available through the static FACET_KEYS
property
of the parent model.
A parent
property will be automagically added to each facet:
Parent p = ;pfacetsfoo = ;assert;
License
MIT