Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda