Attach virtuals to the results of mongoose queries when using `.lean()`
npm install mongoose-lean-virtualsAttach virtuals to the results of mongoose queries when using .lean().
To report a security vulnerability, please use the
Tidelift security contact.
Tidelift will coordinate the fix and disclosure.
``javascript
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 lowercaseres
// won't be in `
const res = await UserModel.find().lean({ virtuals: true });
Mongoose's lean() function typings don't know about virtuals: true, so you need to explicitly set the type when calling lean().VirtualsForModel
This module exports a convenient helper type that returns the virtual property types for a given model.VirtualsForModel
The below example shows using along with lean.
`ts
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
const name: string = doc.name;
const nameUpper: string = doc.nameUpper;
});
``