• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

119
Views
mongoose .find ignores values returned by getters, despite toObject and toJSON getters = true in the Schema

I want to find all the documents whose getters return a particular value. Specifically, in my Position schema, I have a property called uncoveredQuantity, and I want to find all Position documents with uncoveredQuantity = 10.

When I do const positions = await Position.find({uncoveredQuantity : 10}); it returns all documents with various different uncoveredQuantity values, not the ones that are 10! The interesting thing is that my getter function, calculateUncoveredQuantity, does get called when Position.find() gets called, and it prints the console.log statement.

function calculateUncoveredQuantity(this: PositionBaseDocument) {
  console.log("getter called");
  let quantityLeft = this.quantity;
  const dest = this.direction === "in" ? this.closedBy : this.isCloseFor;
  if (!dest) return quantityLeft;
  for (const pos of dest) {
    quantityLeft -= pos.amount;
  }
  return quantityLeft;
}

const PositionCloseSchema = {
  position: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Position",
  },
  amount: {
    type: Number,
    min: 0,
  },
};
const positionSchema = new mongoose.Schema(
  {

    direction: {
      type: String,
      enum: CONSTANTS.directions,
      required: true,
    },
    quantity: {
      type: Number,
      required: true,
      min: 0,
    },

    uncoveredQuantity: {
      type: Number,
      set: calculateUncoveredQuantity,
      default: calculateUncoveredQuantity,
      get: calculateUncoveredQuantity,
    },

    closedBy: {
      type: [PositionCloseSchema],
      required: function (this: PositionBaseDocument) {
        return this.direction === "in";
      },
    },

    isCloseFor: {
      type: [PositionCloseSchema],
      required: function (this: PositionBaseDocument) {
        return this.direction === "out";
      },
    },
  },
  {
    timestamps: true,
    toJSON: {
      getters: true,
    },
    toObject: { 
      getters: true 
    },
  }
);
export const Position = mongoose.model("Position", positionSchema);
about 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error