2013-09-28 34 views
3

我的模式是一樣覆蓋的toJSON如下:[貓鼬]數據從一個異步查詢

var CompanySchema = new Schema({ 
    // 
}); 

CompanySchema.methods.getProducts = function(next) { 
    var Product = require(...); 
    Product.find({...}).exec(function(err, products) { 
    if (err) 
     return next(err) 
    return next(null, products || []); 
    }); 
}; 

我想知道是否有某種方式),包括的getProducts的結果(方法時我序列化公司對象,如:

CompanySchema.methods.toJSON = function() { 
    var obj = this.toObject(); 
    obj.products = this.getProducts(); 
    return obj; 
}; 

在此先感謝您。

+0

不同步,沒有。 – WiredPrairie

+0

你能解釋一下你的問題嗎?你想要達到什麼目的? – RohanJ

回答

2

當然,你可以包括它,只是不同步作爲toJSON的替代品。

原因是您不能在同步方法中使用異步方法(如來自Mongoose的find),如toJSON

所以,你需要使它異步:

CompanySchema.methods.toJSONAsync = function(callback) { 
    var obj = this.toObject(); 
    this.getProducts(function(products) { 
    obj.products = products; 
    }); 
    callback(obj); 
};