-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Discriminators: Return derived model when issuing Find on base model #14593
Comments
This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days |
I'm unable to repro, AFAIK Mongoose does give you the correct discriminator model with 'use strict';
const mongoose = require('mongoose');
run().catch(error => {
console.error(error);
process.exit(-1);
});
async function run() {
await mongoose.connect('mongodb://127.0.0.1:27017/mongoose_test');
const baseModelSchema = new mongoose.Schema({ baseModelProp: String });
const derivedModelSchema = new mongoose.Schema({ derivedModelProp: String });
const baseModel = mongoose.model('BaseModel', baseModelSchema);
const derivedModel = baseModel.discriminator('DerivedModel', derivedModelSchema);
await baseModel.deleteMany({});
const { _id } = await derivedModel.create({ baseModelProp: 'base model test', derivedModelProp: 'derived model test' });
const doc = await baseModel.findById(_id).orFail();
console.log(doc.derivedModelProp); // Prints "derived model test"
console.log(doc instanceof derivedModel); // Prints "true"
} |
This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days |
This issue was closed because it has been inactive for 19 days and has been marked as stale. |
Prerequisites
Mongoose version
8.3.4
Node.js version
v20.11.1
MongoDB version
5.0.16-r1::gentoo
Operating system
Linux
Operating system version (i.e. 20.04, 11.3, 10)
Gentoo
Issue
I have just finished working on updating an old codebase.
As part of this work, I migrated from the old and largely defunct
mongoose-extend-schema
to Mongoose Discriminators.However, there's a key change in functionality which is causing a significant loss in performance.
With
mongoose-extend-schema
, if I did:const result = await baseModel.findOne({ ... });
and the discriminator matched
derivedModel
, it would give me an instance ofderivedModel
.With discriminators, it always gives me an instance of
baseModel
which means that I have to manually convert it, which costs a bunch of additional CPU cycles...This is suboptimal and slow, and I'd really like it if mongoose could give me the correct instance for the model. Is there an option to enable this?
The text was updated successfully, but these errors were encountered: