Unable to populate virtual fields with getter function
Do you want to request a feature or report a bug? report a bug What is the current behavior? populate with getter function should populate the property but it is throwing the following error MongooseError: If you are populating a virtual, you must set the localField and foreignField options
If the current behavior is a bug, please provide the steps to reproduce. Here is my code
const DashboardSchema = new Schema({
userId: {
type: SchemaTypes.ObjectId
}
}, { toJSON: { virtuals: true } });
DashboardSchema.virtual('TopReports').get(function () {
return TopReports.find({ userId: this.userId }).sort('-date').limit(10);
})
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version. node: v10.15.3, mongoose: ^5.5.4 mongodb:4.0.1
I don't think you can populate a virtual that has getter function defined.
You can dashboardQueryResult.TopReports to access the computed value like any other getter though.
To populate virtuals, it requires localField, foreignField property.
They are two different APIs serving different purposes.
Your code as written is quite different from the current populate virtuals API. You need to set localField and foreignField, you cannot populate a virtual with a getter that returns a promise.
I'll keep this open for now because the API that OP suggested is interesting
I can confirm that it works fine in 6.0.13, but is broken in later versions