Skip to content

How can I specify that the auto-populated document should not include or calculate its virtual properties? #121

@KamilTheDev

Description

@KamilTheDev

How can I specify that the auto-populated document should not include or calculate its virtual properties?

For example, I have a clan member schema that includes the User document. I only want to auto-populate the User's name, avatar, avatarFrame and nothing more.

I also had the issue that since the User itself has autopopulate fields (inventory for example), those were being included despite not meant to be. I fixed that by setting maxDepth: 1, not sure if that's the intended fix.

Though that now means since the virtual fields are still trying to be included, it causes an error since it's only intended to be used when the User is fully autopopulated (not needed in this case.)

Member schema:

const memberSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",

    autopopulate: {
      select: "name avatar avatarFrame",
      maxDepth: 1, // fix User inventory being autopopulated and included
    },
  },

  rank: {
    type: String,
    default: "member",
  },

});

const clanSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please add a name value"],
      unique: true,
    },

    members: [memberSchema],
  },

  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

clanSchema.virtual("membersCount").get(function () {
  return this.members.length;
});

User schema:

const userSchema = mongoose.Schema(
  {
    // Account
    name: {
      type: String,
      required: [true, "Please add a name"],
    },

    avatar: {
      type: String,
      default: "default",
    },

    avatarFrame: {
      type: String,
      default: "default",
    },

    bio: {
      type: String,
      default: "default",
    },

    // Inventory - not meant to be auto-populated/included in memberSchema
    inventory: {
      type: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: "InventoryItem",
          autopopulate: true,
        },
      ],
      default: [],
    },
    
  },

  {
    timestamps: true,
  }
);

userSchema.virtual("exampleVirtual").get(function () {
  return "hello world"; // does things with this.inventory - not meant to be included/calculated in memberSchema
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions