1.1.0 • Published 4 months ago

mongoose-lean-virtuals v1.1.0

Weekly downloads
31,937
License
Apache 2.0
Repository
github
Last release
4 months ago

mongoose-lean-virtuals

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

Read the docs here.

Usage

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

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

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

// Now, the `lowercase` property will show up even if you do a lean query
userSchema.plugin(mongooseLeanVirtuals);

// Later

// You **must** pass `virtuals: true` to `lean()`, otherwise `lowercase`
// won't be in `res`
const res = await UserModel.find().lean({ virtuals: true });

TypeScript

Mongoose's lean() function typings don't know about virtuals: true, so you need to explicitly set the type when calling lean(). This module exports a convenient VirtualsForModel helper type that returns the virtual property types for a given model. The below example shows using VirtualsForModel along with lean<TypeOverride>().

import mongooseLeanVirtuals, { VirtualsForModel } from "mongoose-lean-virtuals";

interface ITest {
  name: string
}

const testSchema = new mongoose.Schema(
  { name: { type: String, required: true } },
  {
    virtuals: {
      nameUpper: {
        get() {
          return this.name.toUpperCase();
        }
      }
    }
  }
);

testSchema.plugin(mongooseLeanVirtuals);

const TestModel = mongoose.model('Test', testSchema);

TestModel.findOne().lean<ITest & VirtualsForModel<typeof TestModel>>({ virtuals: true }).orFail().then(doc => {
  const name: string = doc.name;
  const nameUpper: string = doc.nameUpper;
});
1.1.0

4 months ago

1.0.0

8 months ago

0.9.1

3 years ago

0.9.0

4 years ago

0.8.1

4 years ago

0.8.0

4 years ago

0.7.6

4 years ago

0.7.5

4 years ago

0.7.4

4 years ago

0.7.3

4 years ago

0.7.2

5 years ago

0.7.1

5 years ago

0.7.0

5 years ago

0.6.9

5 years ago

0.6.8

5 years ago

0.6.7

5 years ago

0.6.6

5 years ago

0.6.5

5 years ago

0.6.4

5 years ago

0.6.3

5 years ago

0.6.2

5 years ago

0.6.1

5 years ago

0.6.0

5 years ago

0.5.0

6 years ago

0.4.4

6 years ago

0.4.3

6 years ago

0.4.2

6 years ago

0.4.1

6 years ago

0.4.0

6 years ago

0.3.5

6 years ago

0.3.4

6 years ago

0.3.3

6 years ago

0.3.2

7 years ago

0.3.1

7 years ago

0.3.0

7 years ago

0.2.0

7 years ago

0.1.1

8 years ago

0.1.0

8 years ago