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);