【问题标题】:Query mongoose multiple models查询mongoose多个模型
【发布时间】:2015-02-27 18:13:04
【问题描述】:

我正在使用 MEAN 堆栈 开发一个小应用程序,但无法查询我的模型。

我有 4 个模型,在不同的文件中。

这是发票模型:

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 个其他模型。 到目前为止一切正常,我可以使用来自员工、产品和客户的数据填充发票。

但我很迷茫:

我想为每个员工提供他们的总销售额(当他们创建发票时,数量 * 价格)。

如何为每个 Invoice 创建增加 Employee Model 中的 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 的服务来发布数据。

谢谢!

【问题讨论】:

    标签: javascript angularjs node.js mongodb mongoose


    【解决方案1】:

    看起来有点直截了当。但我猜下面的例子就是你要找的。​​p>

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

    您可能希望添加验证以确保您的发票已创建。并为保存方法添加回调。

    【讨论】:

    • 很好,但我需要“引用”我猜的 Employee 模型,因为它会产生错误 TypeError: Object # has no method 'findById' (对于 Employee.findById 行)。由于我的模型位于单独的文件中,我不知道该怎么做,我想避免 RequireJS 只是为了这个需要。无论如何,谢谢你的回答!
    • 这很奇怪。你可以试试 findOne。我将更新我的示例。
    猜你喜欢
    • 2014-01-09
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2017-06-04
    相关资源
    最近更新 更多