Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose temporary calculated field

For a basic example I have a schema:

var testSchema = new Schema({
  op1    : Number,
  op2     : Number
});

then I want to have a "total" field that's not stored in DB but automatically computed after retrieval, and possibly can be used for Mongoose's query.sort.

I.e.

total = op1 + op2

then use myTestModel.find({}).sort(total).execFind(...);

Is this possible?

like image 476
Manny Avatar asked Feb 16 '23 19:02

Manny


1 Answers

MongoDB doesn't allow you to calculate fields with normal queries, however, you can do this with the aggregation framework. You'd do that like this:

myTestModel.aggregate(
    { $match: {} }, // your find query
    { $project: {
        op1: 1, // original fields
        op2: 1,
        total: { $add: ['$op1', '$op2' ] } // calculated field
    } },
    { $sort: { total: 1 } },

    // And then the normal Mongoose stuff:
    function (err, res) {
    }
);

See also: http://mongoosejs.com/docs/api.html#model_Model.aggregate

like image 64
Derick Avatar answered Feb 27 '23 04:02

Derick