2015-06-19 183 views
0

我试图做两个queryies,然后将它们结合起来,并将其发送回客户端不包括增值...这里是我的中间件:猫鼬模型时返回

这是控制器的方法所谓

exports.read = function(req, res) { 
    console.log(req.shipment.vendorInvoices); // note this prints the data I am looking for 
    res.jsonp(req.shipment); 
}; 

但随后在客户机上的所有我得到的回复是所有的值,但vendorInvoices的:

{ 
    __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"} 
} 

我被卡住了,为什么不能通过?

回答

0

两种可能性

  1. 返回一个普通的对象。

    var s = shipment.toJSON(); s.vendorInvoice = vendorInvoice;

  2. 执行toJSON方法来检查增加的值。 http://mongoosejs.com/docs/guide.html#toJSON

+0

猫鼬'.toJSON()'是一个用于在JSON.stringify()之前清理/定制对象的方法(在进行字符串化之前,它总是检查对象是否为'.toJSON'方法)。可以说,它实际上不是直接被调用的。使用Mongoose'.toObject()'更好,因为它专门用于以这种方式创建“惰性”对象。如果您想“激活”'.JSON',请在模型实例上使用'JSON.stringify'。 –

+0

谢谢,简单的对象是有道理的。我假设我没有看到数据的原因是因为本地toJSON没有选择它。必须在方法检查的地方进行某种键注册。谢谢! –

1

您可以尝试通过调用查询链lean()方法如下JavaScript对象,而不是猫鼬模型实例返回平地

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

});