Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.88k stars 3.83k forks source link

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

Open vkarpov15 opened 3 years ago

vkarpov15 commented 3 years ago

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

hasezoey commented 2 years ago

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?

vkarpov15 commented 1 year ago

@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.

Jokero commented 1 year ago

+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