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-lean-virtuals with all npm packages installed. Try it out:

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

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

mongoose-lean-virtuals v0.1.1

Attach virtuals to the results of mongoose queries when using `.lean()`

mongoose-lean-virtuals

Attach virtuals to the results of mongoose queries when using .lean()

Usage

const mongooseLeanVirtuals = require('mongoose-lean-virtuals');

examples

It attaches virtuals to result of find, findOne, and findOneAndUpdate if lean


    const schema = new mongoose.Schema({
      name: String
    });

    schema.virtual('lowercase').get(function() {
      return this.name.toLowerCase();
    });

    schema.plugin(mongooseLeanVirtuals);

    const Model = mongoose.model('Test', schema);

    return Model.create({ name: 'Val' }).
      then(() => Promise.all([
        // You **must** pass `virtuals: true` to `lean()`
        Model.find().lean({ virtuals: true }),
        Model.findOne().lean({ virtuals: true }),
        Model.findOneAndUpdate({}, { name: 'VAL' }).lean({ virtuals: true })
      ])).
      then(results => {
        const [findRes, findOneRes, findOneAndUpdateRes] = results;
        assert.equal(findRes[0].lowercase, 'val');
        assert.equal(findOneRes.lowercase, 'val');
        assert.equal(findOneAndUpdateRes.lowercase, 'val');

        // Mongoose has an `id` virtual by default that gets the `_id` as a
        // string.
        assert.equal(findRes[0].id, findRes[0]._id.toString());
        assert.equal(findOneRes.id, findOneRes._id.toString());
        assert.equal(findOneAndUpdateRes.id, findOneAndUpdateRes._id.toString());
      });
  

It lets you choose which virtuals to apply

If you specify a list of virtuals in lean(), this plugin will only apply those virtuals. This lets you pick which virtuals show up.


    const schema = new mongoose.Schema({
      name: String
    }, { id: false });

    schema.virtual('lowercase').get(function() {
      return this.name.toLowerCase();
    });
    schema.virtual('uppercase').get(function() {
      return this.name.toUpperCase();
    });

    schema.plugin(mongooseLeanVirtuals);

    const Model = mongoose.model('Test2', schema);

    return Model.create({ name: 'Val' }).
      then(() => Model.findOne().lean({ virtuals: ['uppercase'] })).
      then(result => {
        assert.equal(result.uppercase, 'VAL');
        assert.ok(!result.lowercase);
      });
  
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