2015-06-19 182 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(); 
      }); 

});