New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mongoose-lean-virtuals

Package Overview
Dependencies
Maintainers
0
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongoose-lean-virtuals

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

  • 1.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
90K
decreased by-15.05%
Maintainers
0
Weekly downloads
 
Created
Source

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;
});

Keywords

FAQs

Package last updated on 05 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc