Mongoose: find by calculated field

Viewed 147

I have a schema like this:

    const facturacionSchema = mongoose.Schema({
       PrecioCantidad: Number,
       Cantidad: Number,
       Total: {
           type: Number,
           get: function() {
               return this.PrecioCantidad * this.Cantidad
           }
       }
    });
    module.exports = mongoose.model('Facturacion', facturacionSchema);

And I want to find documents by "Total", like:

Facturacion.find({ Total: 1000 });

"Total" field is not in the database documents, is a calculated field. I don't mind if I have to do something like:

Facturacion.find({ PrecioCantidad * Cantidad: 1000 });

but I don't know how to find based on a calculation of two fields.

Thanks.

1 Answers

First of all, I dont think you can access other fields in a getter (correct me if I'm wrong)

Then, to find documents with (PrecioCantidad * Cantidad) is as below (just a workaround, of course, there are many ways of doing it)

Facturacion.find({ $expr: { $eq: [ { $multiply: ["$PrecioCantidad", "$Cantidad"]} ], 1000}})

UPDATE

For getting other fields in a getter, use virtual

Related