我正在尝试执行两个查询,然后将它们组合起来并将其发送回客户端...这是我的中间件:
exports.shipmentByID = function(req, res, next, id) {
Shipment.findById(id)
.populate('user', 'displayName')
.exec(function(err, shipment) {
if (err) return next(err);
if (! shipment) return next(new Error('Failed to load Shipment ' + id));
VendorInvoice.find({ shipment: id })
.exec(function (err, vendorInvoices) {
if (err) return next(err);
if (! vendorInvoices) return next(new Error('Failed to load Shipment ' + id));
shipment.vendorInvoices = vendorInvoices;
req.shipment = shipment;
next();
});
});
};
以及被调用的 Controller 方法
exports.read = function(req, res) {
console.log(req.shipment.vendorInvoices); // note this prints the data I am looking for
res.jsonp(req.shipment);
};
但是在客户端上我得到的只是除 vendor 发票之外的所有值:
{
__v: 0
_id: "5583af682b46ec9353963dc4"
created: "2015-06-19T05:58:00.434Z"
dateInvoiced: "2015-06-18T07:00:00.000Z"
shipmentId: "12345"
user: {_id: "549268852f54d06f4d0720ce", displayName: "troy Cosentino"}
}
我被卡住了,为什么不能通过?
最佳答案
您可以尝试通过调用 lean()
返回一个纯 JavaScript 对象而不是 Mongoose 模型实例。查询链上的方法如下:
Shipment.findById(id)
.populate('user', 'displayName')
.lean()
.exec(function(err, shipment){
if (err) return next(err);
if (! shipment) return next(new Error('Failed to load Shipment ' + id));
VendorInvoice.find({ shipment: id })
.exec(function (err, vendorInvoices) {
if (err) return next(err);
if (! vendorInvoices) return next(new Error('Failed to load Shipment ' + id));
shipment.vendorInvoices = vendorInvoices;
req.shipment = shipment;
next();
});
});
关于javascript - Mongoose 模型不包括返回时的附加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931977/