mongoose-normalizr

Generate normalizr schemas from mongoose schemas!

View the Project on GitHub

current version Build Status Coverage Status semantic-release Commitizen friendly

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.

Installation

npm install --save mongoose-normalizr

Usage

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"
      }
    }
  }
}

Features

mongooseNormalizr(schemas)

See our tests for examples!