Skip to content

Mongoose Schema Array element getter is not called, when it should be #9889

@ahmednaser94

Description

@ahmednaser94

Do you want to request a feature or report a bug?
bug

What is the current behavior?
When using getters inside schema types, if the property of the schema is an Array, getter of an element is not called when it should be

  // Part of the Schema
    groups: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Group',
        get: function (v: Schema.Types.ObjectId) {
          console.log(`🚀 ~ GET groups ~ line 160`)
          return v ? v.toString() : undefined
        },
        set: function (v: any) {
          console.log(`🚀 ~ SET groups ~ line 164`)
          return v
        },
      }
    ],
    createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      get: function (v: Schema.Types.ObjectId) {
        console.log(`🚀 ~ GET created by ~ line 174`)
        return v ? v.toString() : undefined
      },
      set: function (v: any) {
        console.log(`🚀 ~ SET created by ~ line 178`)
        return v
      },
    }

Note: just logging to detect which one is fired during operations

If the current behavior is a bug, please provide the steps to reproduce.

https://gist.github.com/ahmednaser94/f0b2e10fb4927da28dbec6d48fdd465a

What is the expected behavior?
It should call get: of groups property and createdBy property of user model

Expected log in terminal

~ GET groups ~ line 160
~ GET created by ~ line 174

What actually happen in 2 different scenarios

  1. When log the inserted document
    it prints
~ GET created by ~ line 174

It didn't call get: of groups property!, but called get: of createdBy

  1. When query this document by its _id using findById method
    it prints
~ SET groups ~ line 164
~ GET created by ~ line 174

It didn't call get: of groups property also!, but called set: instead !!!

why set: of groups called!! it should call get: not set:

it only calls get: inside createdBy, but not inside groups

Also, be noted that, createdBy is one ObjectID, but groups is array of ObjectID

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

  • Mongoose: 5.11.14
  • Mongodb: 4.4.3
  • Node.Js: 14.15.4
{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "outDir": "dist",
    "removeComments": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "moduleResolution": "Node"
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions