How to create an abstract function to get data from mongoose?

I want to create a abstract function to get all collections with mongoose and it will receive or not the parameters to use in the populate method. So, I have this code now:

async function getCollection(model, relatedFields) {   
 if (!relatedFields) relatedFields = [];  
    try {
      const collection = await model.find()
        .populate(relatedFields[0] ? relatedFields[0] : '')
        .populate(relatedFields[1] ? relatedFields[1] : '')
        .populate(relatedFields[2] ? relatedFields[2] : '');
      return collection;
    } catch (err) {
      throw err;
    }
 }

It works, but this repeated populate method seems to me inefficient.

There is a way to do this smarter?
Thanks! 🙂

29 thoughts on “How to create an abstract function to get data from mongoose?”

Leave a Comment