数据模型
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)
会返回正确的信息。
我想要做的是在save
文档上运行InvoiceSchema
之前访问数据以配置预配置数据。
在聚合回调中,this
引用全局节点对象,而不是InvoiceSchema
实例。
如何访问聚合返回的信息并将其设置在引用this
实例的InvoiceSchema
上?
我想在回调中做什么的例子:
data.map(function(doc) {
if(doc._id === 280) {
this.qty_280 = doc.count;
this.total_280 = doc.count * this.rate_280;
}
}
答案 0 :(得分:0)
我希望聚合回调中的上下文发生变化,试试这个[更新]。
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();
});
});