mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

https://github.com/mongoosejs/mongoose-lean-virtuals/issues/52

Open vkarpov15 opened this issue 4 years ago • 3 comments

https://github.com/mongoosejs/mongoose-lean-virtuals/issues/52

vkarpov15 avatar Jul 02 '21 17:07 vkarpov15

what exactly is this issue supposed to change in mongoose? from what i can tell, this could just be a schema.plugin(fn, opt) option or some other global plugin option or even some custom schema option?

hasezoey avatar Sep 05 '22 10:09 hasezoey

@hasezoey my mistake, I sometimes open issues in Mongoose to keep track of issues in other repos. Hard to keep track of issue reports in all the other Mongoose-related repos.

vkarpov15 avatar Sep 27 '22 23:09 vkarpov15

+1 for it. I prefer using lean and id instead of _id. To have it working, I need to extend inferred schema type by id field and use lean({ virtuals: true }) everywhere. And of course it's easy to forget to add { virtuals: true } in some place.

const countrySchema = new Schema({
    name: { required: true, type: Map, of: String }
});

countrySchema.plugin(leanVirtuals); // can be moved to global level, i.e. mongoose.plugin(leanVirtuals);

export type CountryRaw = InferSchemaType<typeof countrySchema>;
export type Country = CountryRaw & { id: string }; // I might have other virtuals too

// call
const CountryModel = model<Country>('Country', schema);
CountryModel.find().lean({ virtuals: true }).exec();

Ideally, it would be nice to be able to specify an option for the plugin:

countrySchema.plugin(leanVirtuals, { enabledByDefault: true });
// or
mongoose.plugin(leanVirtuals, { enabledByDefault: true });

And then use lean without any option:

CountryModel.find().lean().exec();

Actually, there is no way to set global options in mongoose right now (or I don't know about it). For example, I'm using timestamps: { createdAt: true, updatedAt: false } in all schemas, better approach is to specify it on mongoose level

Jokero avatar Mar 05 '23 13:03 Jokero