Skip to content

Virtual declared after model creation, doesn't work #14296

@chumager

Description

@chumager

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.1.1

Node.js version

20.11.0

MongoDB server version

6.0.12

Typescript version (if applicable)

No response

Description

If I define a virtual after model declaration, the virtual only works callingtoJSON() to document.

For now I've to use applyGetters() to the virtualType to get the value.

Steps to Reproduce

import db from "mongoose"; //await db.connect("mongodb://127.0.0.1:27017/test"); const Schema = new db.Schema({ field: String }); Schema.virtual("virtual1").get(function () { return this.field + " virtual1"; }); Schema.virtual("virtual2").get(function () { return this.virtualAfter + " virtual2"; }); Schema.virtual("virtual3").get(function () { return this.constructor.schema.virtualpath("virtual4").applyGetters(undefined, this) + " virtual3"; }); const Model = db.model("model", Schema); Model.schema.virtual("virtual4").get(function () { return this.field + " virtual4"; }); const doc = new Model({field: "test"}); console.log("doc", doc); console.log("doc JSON", doc.toJSON({virtuals: true})); console.log("doc.virtual1", doc.virtual1); console.log("doc.virtual2", doc.virtual2); console.log("doc.virtual3", doc.virtual3); console.log("doc.virtual4", doc.virtual4); console.log("doc.virtual1 applyGetters", Schema.virtualpath("virtual1").applyGetters(undefined, doc)); console.log("doc.virtual2 applyGetters", Schema.virtualpath("virtual2").applyGetters(undefined, doc)); console.log("doc.virtual3 applyGetters", Schema.virtualpath("virtual3").applyGetters(undefined, doc)); console.log("doc.virtual4 applyGetters", Schema.virtualpath("virtual4").applyGetters(undefined, doc));

Expected Behavior

If doc.toJSON() works with a virtual defined after model, I should be able to get the virtual directly.

In the docs the only restriction is to avoid hook definitions after model.

Metadata

Metadata

Assignees

No one assigned

    Labels

    priorityAutomatically set for Mongoose Pro subscribers

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions