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.
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With