Javascript 查询mongoose多模型
我正在开发一个带有平均堆栈的小应用程序,我很难查询我的模型 我有4个模型,在不同的文件中 以下是发票模型:Javascript 查询mongoose多模型,javascript,angularjs,node.js,mongodb,mongoose,Javascript,Angularjs,Node.js,Mongodb,Mongoose,我正在开发一个带有平均堆栈的小应用程序,我很难查询我的模型 我有4个模型,在不同的文件中 以下是发票模型: var invoiceSchema = new Schema ({ employee : { type: Schema.Types.ObjectId, ref: 'Employee' }, customer : { type: Schema.Types.ObjectId, ref: 'Customer' }, products : { type: Schema.Ty
var invoiceSchema = new Schema ({
employee : { type: Schema.Types.ObjectId, ref: 'Employee' },
customer : { type: Schema.Types.ObjectId, ref: 'Customer' },
products : { type: Schema.Types.ObjectId, ref: 'Product' },
priced : Number,
qty : Number,
comment : String,
date : Date
});
var Invoice = mongoose.model('Invoice',invoiceSchema);
exports.createInv = function (req, res) {
Invoice.create({
employee : req.body.employee,
customer : req.body.customer,
products : req.body.products,
priced : req.body.priced,
qty : req.body.qty,
comment : req.body.comment,
date : req.body.date
}, function(err) {
if (err)
return res.send(err);
});
}
如您所见,它指向前3个字段的3个其他模型。
到目前为止一切正常,我能够用来自员工、产品和客户的数据填充发票
但这样做让我很迷茫:
我想为每个员工提供销售总额(当他们创建发票时,数量*价格)
如何为每个发票创建增加员工模型中的totalSales字段
员工模式:
var employeeSchema = new Schema ({
firstname : String,
lastname : {type : String, unique : true},
age : Number,
dept : String,
mail : String,
phone : String,
totalsales : Number
});
var Employee = mongoose.model('Employee',employeeSchema);
我使用带有$http的服务发布数据
谢谢大家! 似乎有点直截了当。但我猜下面的例子就是你想要的
exports.createInv = function (req, res) {
Invoice.create({
employee : req.body.employee,
customer : req.body.customer,
products : req.body.products,
priced : req.body.priced,
qty : req.body.qty,
comment : req.body.comment,
date : req.body.date
}, function(err) {
if (err)
return res.send(err);
});
Employee.findOne({"_id":req.body.employee}, function (err, doc) {
var salesPrice = req.body.priced * req.body.qty;
doc.totalSales += salesPrice;
doc.save();
})
}
您可能希望添加验证以确保您的发票已创建。还向save方法添加了一个回调。很好,但我需要“引用”我猜的员工模型,因为它会生成一个错误类型error:Object#没有方法“findById”(用于Employee.findById行)。由于我的模型在不同的文件中,我不知道如何做到这一点,我想避免仅仅为了这个需要而使用RequireJS。无论如何,谢谢你的回答!真奇怪。那你可以试试findOne。我将更新我的示例。