简体   繁体   English

查询mongoose多个模型

[英]Query mongoose multiple models

I'm developing a little app with the MEAN stack and I'm having trouble to query my models. 我正在使用MEAN堆栈开发一个小应用程序,我无法查询我的模型。

I have 4 models, in separate files. 我有4个模型,在单独的文件中。

Here's the Invoice model : 这是发票模型:

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);
    });
}

As you can see it points to the 3 others models for the 3 first fields. 正如您所看到的,它指向3个第一个字段的其他3个模型。 So far all is working, I'm able to populate an invoice with the data coming from Employee, Product and Customer. 到目前为止一切正常,我能够使用来自员工,产品和客户的数据填写发票。

But I'm quite lost for doing that : 但是我很遗憾这样做:

I'd like to have for each Employee, the total of their sales (when they create an invoice, qty * price). 我想为每位员工提供他们的销售总额(当他们创建发票时,数量*价格)。

How to Increment the totalSales field in the Employee Model for each Invoice creation ? 如何为每个发票创建增加员工模型中totalSales字段?

Employee Model : 员工模型:

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);

I use a Service with $http to post datas. 我使用带有$ http的服务来发布数据。

Thank you ! 谢谢 !

Seems kind of straight forward. 看起来很直截了当。 But I'm guessing that the example below is what you're looking for. 但我猜这个例子是你正在寻找的。

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();
   })
}

You probably want to add validation to make sure that your invoice got created. 您可能希望添加验证以确保创建发票。 And also add a callback to the save-method. 并且还向save-method添加回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM