mongoose-reference

2.0.0 • Public • Published

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

Key Type Description
models Array Define all allowed reference types (enum). Must be the same as the name of the registered Schemas
key String Define your custom key. (Default: reference or references)
multiple Boolean Set to true if you want to have multiple references
modelKey String Define your custom key for model value. (Default: onModel)
referenceKey String Define 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

Package Sidebar

Install

npm i mongoose-reference

Weekly Downloads

5

Version

2.0.0

License

MIT

Unpacked Size

5.49 kB

Total Files

5

Last publish

Collaborators

  • crsten