Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including mongoose-populate-virtuals with all npm packages installed. Try it out:

require("mongoose/package.json"); // mongoose is a peer dependency. var mongoosePopulateVirtuals = require("mongoose-populate-virtuals")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

mongoose-populate-virtuals v1.0.3

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

mongoose-populate-virtuals

Build Status NPM version

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

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.

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

Author.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:

  • ref Name of the mongoose model (required).
  • foreignKey Key on the model of the populated virtual (required).
  • localKey Key on the model being populated (required).
  • match Query used for find() or fineOne.
  • options Mongo options such as sort and limit.
  • select Mongoose's .select() argument.
  • singular Use singular reference instead of array.
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free