Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Mongoose]Override toJSON with data from an async query

My schema is like the following:

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 || []);
  });
};

I want to know if there is some way to include the result of getProducts() method when I serialize a Company object, something like:

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

Thank you in advance.

like image 595
VinhBS Avatar asked Nov 02 '22 13:11

VinhBS


1 Answers

Sure, you can include it, just not synchronously as a replacement for toJSON.

The reason is that you can't use an asynchronous method (like find from Mongoose) in a synchronous method, like toJSON.

So you'd need to make it async:

CompanySchema.methods.toJSONAsync = function(callback) {
  var obj = this.toObject();
  this.getProducts(function(products) {
    obj.products = products;
  });
  callback(obj);
};
like image 155
WiredPrairie Avatar answered Nov 08 '22 05:11

WiredPrairie