Generate normalizr schemas from mongoose schemas!
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"
}
}
}
}
0.1.1
.mongooseNormalizr(schemas)
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
: If false
, produces an empty normalizr schema and doesn’t follow any references. Defaults to value of enable
.reference
: If false
, other produced schemas will ignore references to this schema. Defaults to value of enable
.enable
: Shorthand for define
&& reference
. Defaults to true
.See our tests for examples!