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
Dynamic virtual populate not working on subdocument with separate schema #12363
Comments
import mongoose from 'mongoose';
const nestedSchema = new mongoose.Schema({
targetType: String,
targetId: mongoose.Schema.Types.ObjectId,
}, {
virtuals: {
target: {
options: {
ref: (doc: any) => {
// doc should be the sub document
// but instead, it is the parent document
console.debug(doc);
return doc.targetType;
},
localField: 'targetId',
foreignField: '_id',
justOne: true,
}
}
}
});
const parentSchema = new mongoose.Schema({
nested: {
type: nestedSchema
},
});
const NestedDynamicVirtualPopulateTest = mongoose.model('NestedDynamicVirtualPopulateTest', parentSchema);
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
const target = new NestedDynamicVirtualPopulateTest({});
await target.save();
const parent = new NestedDynamicVirtualPopulateTest({
nested: {
targetType: (target.constructor as typeof NestedDynamicVirtualPopulateTest).modelName,
targetId: target._id,
}
});
await parent.save();
await parent.populate('nested.target');
console.log(parent);
console.log('=============');
console.log(parent.nested);
console.log('=================');
console.log(parent.nested.target);
console.log('======================')
}
run(); |
Hi @IslandRhythms, the code snippet in my initial comment was not properly typed, because I thought the type definition does not do much help demonstrating the issue and will make the snippet unnecessarily long. So I just put |
Hi @IslandRhythms, I think the "typescript" label on this issue is not appropriate. The typing error in your comment is not related to this issue. And this issue is not related to typescript. |
Prerequisites
Mongoose version
6.5.4
Node.js version
16.15.0
MongoDB server version
4.2.1
Description
Seems to be related to #8277 and #8742
When using dynamic ref on child schema
{ ref: (doc) => doc.refType }
, the passed indoc
is the parent document, not the subdocument, causing dynamic ref path not correctly returned.I tried both
virtuals
option in schema constructor options and schemavirtual()
method, tried bothref
andrefPath
in virtual options, none works.Steps to Reproduce
Expected Behavior
Since the virtual is defined on the child schema, the dynamic ref path should be relative to the subdocument, not the parent document.
The text was updated successfully, but these errors were encountered: