Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
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 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!