Generate normalizr schemas from mongoose schemas!
normalizr and mongoose both define relationships between the same objects. Define the mongoose relationships and get the same normalizr relationships without repeating yourself.
npm install --save mongoose-normalizr
import mongoose from 'mongoose';
import normalizr from 'normalizr';
import mongooseNormalizr from 'mongoose-normalizr';
const Foo = mongoose.Schema({
bar: { ref: 'Bar', type: mongoose.Schema.Types.ObjectId },
});
const Bar = mongoose.Schema({
foos: [{ ref: 'Foo', type: mongoose.Schema.Types.ObjectId }],
});
const normalizrs = mongooseNormalizr({
Foo,
Bar,
});
const denormalizedFoo = {
id: 'foo1',
bar: {
id: 'bar1',
foos: [
{
id: 'foo2',
},
{
id: 'foo3',
bar: {
id: 'bar2',
},
},
],
},
};
console.log('normalized:', normalizr.normalize(denormalizedFoo, normalizrs.foos));
{
"result": "foo1",
"entities": {
"foos": {
"foo1": {
"id": "foo1",
"bar": "bar1"
},
"foo2": {
"id": "foo2"
},
"foo3": {
"id": "foo3",
"bar": "bar2"
}
},
"bars": {
"bar1": {
"id": "bar1",
"foos": [
"foo2",
"foo3"
]
},
"bar2": {
"id": "bar2"
}
}
}
}
- Built specifically for the browser! Works server-side, as well.
- Traverses arrays and objects to find deep references.
- Supports Subdocuments.
- Supports Populateable Virtuals.
- Supports Dynamic References.
- It does this by generating normalizr Unions. Unions don't normalize to an id like Entities do.
- Supports Discriminators.
- It does this by generating normalizr Unions. Unions don't normalize to an id like Entities do.
- Works on all versions of normalizr, all the way back to
0.1.1
.
schemas
: required: An object mapping mongoose model names (not collection names) to mongoose schemas. Instead of a mongoose schema, you may supply an object with the following properties:schema
: required The mongoose schema to use.define
: Iffalse
, produces an empty normalizr schema and doesn't follow any references. Defaults to value ofenable
.reference
: Iffalse
, other produced schemas will ignore references to this schema. Defaults to value ofenable
.enable
: Shorthand fordefine
&&reference
. Defaults totrue
.
See our tests for examples!