Mongoose temporary calculated field
mongodb, mongoose
Solution
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
Problem
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?