2.0.0 • Published 4 years ago

mongoose-reference v2.0.0

Weekly downloads
9
License
MIT
Repository
github
Last release
4 years ago

mongoose-reference

Build Status npm npm

Mongoose "plugin" for management of dynamic references.

Installation

npm install --save mongoose-reference

Usage

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Reference = require("mongoose-reference");

let YourSchema = new Schema({
  title: String,
  description: String,
  author: String,
  ...Reference({ models: ["Company", "Group"], multiple: true })
});

After implementing mongoose-reference extends your Schema with reference or references.

E. g.

// Example above after beeing extended
let YourSchema = new Schema({
  title: String,
  description: String,
  author: String,
  references: [
    {
      ref: {
        type: Schema.Types.ObjectId,
        required: true,
        refPath: "references.onModel"
      },
      onModel: {
        type: String,
        required: true,
        enum: ["Company", "Group"]
      }
    }
  ]
});

Options

KeyTypeDescription
modelsArrayDefine all allowed reference types (enum). Must be the same as the name of the registered Schemas
keyStringDefine your custom key. (Default: reference or references)
multipleBooleanSet to true if you want to have multiple references
modelKeyStringDefine your custom key for model value. (Default: onModel)
referenceKeyStringDefine your custom key for reference value. (Default: ref)

Important! Mongoose has some reserved keys that will throw an error if used. See list here: Reserved keys

Example

Reference({
  models: [...],
  key: 'CustomKey',
  multiple: true
})

License

The MIT License Copyright (c) Carsten Jacobsen