javascript - Mongoose 模型不包括返回时的附加值

标签 javascript node.js mongodb

我正在尝试执行两个查询,然后将它们组合起来并将其发送回客户端...这是我的中间件:

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/

相关文章:

node.js - 使 *.crt *.pem 证书在 Docker 容器上运行的 Azure 应用服务内可用

java - 单元测试 spring data mongodb 自定义转换器

mongodb - 从自下而上的方法查询 Ember 和 Firebase 数据?

javascript - 单独的导航下降必须有单独的内容,显示相同的内容

node.js - 错误 : GoogleMapsAPI is not defined for node-googlemaps

javascript - Google Apps 脚本 - 将 UrlFetch 响应转换为数组

mysql - 使用 Sequelize 计算关联条目

MongoDB MongoError : Out of memory

javascript - 谷歌地图点击事件无法完全正确工作

javascript - 如何在 AJAX 请求完成之前正确运行微调器?