Mongoose middleware to pre aggregate data and then use that data to save document

Data Model

var mongoose = require('mongoose');
var Casenote = mongoose.model('Casenote');

var InvoiceSchema = new mongoose.Schema({
  start_date: {type: Date},
  end_date: {type: Date},
  created_on: {type: Date, default: Date.now},
  invoice_num: String,
  month: String,
  type: String,
  provider_num: String,
  rate_280: Number,
  rate_285: Number,
  rate_286: Number,
  rate_287: Number,
  rate_288: Number,
  rate_290: Number,
  qty_280: String,
  qty_285: String,
  qty_286: String,
  qty_287: String,
  qty_288: String,
  qty_290: String,
  total_280: Number,
  total_285: Number,
  total_286: Number,
  total_287: Number,
  total_288: Number,
  total_290: Number
});

InvoiceSchema.pre('save', function(next) {

Casenote.aggregate([
    {
      $match: {
      "created_on": {"$gte": new Date(this.start_date)},
      "created_on": {"$lte": new Date(this.end_date)}
      }
    },
    {
      $group: {
        _id: "$pov",
        count: {$sum: 1}
      }
    }
  ], function(err, data) {
    console.log(data);
  });

  next();
});

mongoose.model('Invoice', InvoiceSchema);

console.log(data) returns the correct information.

What I want to do is access the data to configure pre-configure data before save is run on the InvoiceSchema document.

In the aggregate callback, this refers to the global node object and not to the InvoiceSchema instance.

How do I access the information returned by aggregation and set it on the this that references InvoiceSchema instance?

Example of what I'd like to do in callback:

data.map(function(doc) {
    if(doc._id === 280) {
       this.qty_280 = doc.count;
       this.total_280 = doc.count * this.rate_280;
    }
}

Answers


I hope the context changes inside the aggregate callback, try this[Updated].

InvoiceSchema.pre('save', function(next) {
    var self = this;
    Casenote.aggregate([
    {
      $match: {
      "created_on": {"$gte": new Date(this.start_date)},
      "created_on": {"$lte": new Date(this.end_date)}
      }
    },
    {
      $group: {
        _id: "$pov",
        count: {$sum: 1}
      }
    }
     ], function(err, data) {
      console.log(data, 'self has the invoice schema', self);
      data.map(function(doc) {
        if(doc._id === 280) {
          self.qty_280 = doc.count;
          self.total_280 = doc.count * self.rate_280;
        }
      });
        next();
    });
});

Need Your Help

B2B programming on iPad (and iPhone)

iphone ipad b2b

I'm digging through iPad/iPhone programming options/opportunities. What makes me wonder is:

resusable function in codeigniter

php codeigniter code-reuse helper

Almost in all function in most of my controller i have to see to same things. i.e