alexmingoia / mongoose-populate-virtuals

Extend Mongoose 4+ population with virtual attributes that can be populated in either direction.
33 stars 3 forks source link

mongoose-populate-virtuals

Build Status NPM version

Replace Mongoose 4+ population with virtual attributes that can be populated in either direction.

Note: This module changes the functionality of .populate(). You must populate virtual attributes instead of ObjectId attributes, and adding a ref option to ObjectId attributes no longer does anything.

Usage

Wrap mongoose:

var mongoose = require('mongoose-populate-virtuals')(require('mongoose'));

Create document references to populate by defining virtual attributes with ref, localKey and foreignKey options.

AuthorSchema.virtual('books', {
  ref: 'Book',
  foreignKey: 'authorId',
  localKey: '_id'
});

AuthorModel.find().populate('books').exec(...);

Remember virtual attributes are not persisted to the DB. Virtuals are not included in the model's .toObject() or .toJSON() methods unless the options include { virtuals: true }.

Options

Options for populate virtuals: