mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Unable to populate virtual fields with getter function

Open itsvkv opened this issue 6 years ago • 4 comments

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

itsvkv avatar May 04 '19 13:05 itsvkv

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.

drenther avatar May 05 '19 06:05 drenther

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.

vkarpov15 avatar May 07 '19 15:05 vkarpov15

I'll keep this open for now because the API that OP suggested is interesting

vkarpov15 avatar May 07 '19 15:05 vkarpov15

I can confirm that it works fine in 6.0.13, but is broken in later versions

illarion avatar Dec 17 '21 15:12 illarion