Node.js Mongoose中间件预先聚合数据,然后使用该数据保存文档
数据模型Node.js Mongoose中间件预先聚合数据,然后使用该数据保存文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,数据模型 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,
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(数据)
返回正确的信息
我要做的是在InvoiceSchema
文档上运行save
之前访问数据以配置预配置数据
在聚合回调中,此
引用全局节点对象,而不是InvoiceSchema
实例
如何访问聚合返回的信息并将其设置在引用InvoiceSchema
实例的this
上
我希望在回调中执行的操作示例:
data.map(function(doc) {
if(doc._id === 280) {
this.qty_280 = doc.count;
this.total_280 = doc.count * this.rate_280;
}
}
我希望聚合回调中的上下文发生更改,请尝试此[更新]
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();
});
});
最好将
next()
置于if
块之外,因为所有与if条件不匹配的对象都必须调用next。是的,我关心的是next()
会被多次调用吗?是的,你是对的。然后next应该被移到data.map
之外。谢谢