Mongoose and Node JS - improve find

52 views Asked by At

I have collection A and collection B. I need to get all B (distinct preferably) that are in A that have a simple elemMatch. In this case A is Formation and B is Course. I only need the fields that are being currently fetched and nothing else.

At the moment I have this, which is working:

Formation.find({}, { _id: 0, course: 1 }).elemMatch('trainees', { 'trainee': traineeID }).populate('course', '_id name').exec(function(err, formations) {
    if(err) return ;
    console.log(formations);

    // to fix the array format
    var courses = formations.map(function(f){ return f.course });
    console.log(courses);

    // to delete repeated values
    courses = courses.filter((item, index, self) => self.findIndex((i) => { return i._id === item._id; }) === index);
    console.log(courses)
});

Outputs - example:

First:
[ { course: { _id: 582f189764111029a85f77d9, name: 'Outro' } },
  { course: { _id: 581b6ff52814533153ed3790, name: 'Microsoft Excel - Bases de Dados' } },
  { course: { _id: 581b6ff52814533153ed3790, name: 'Microsoft Excel - Bases de Dados' } } ]

Second:
[ { _id: 582f189764111029a85f77d9, name: 'Outro' },
  { _id: 581b6ff52814533153ed3790, name: 'Microsoft Excel - Bases de Dados' },
  { _id: 581b6ff52814533153ed3790, name: 'Microsoft Excel - Bases de Dados' } ]

Third:
[ { _id: 582f189764111029a85f77d9, name: 'Outro' },
  { _id: 581b6ff52814533153ed3790, name: 'Microsoft Excel - Bases de Dados' } ]

Is there a way I can improve this in order to remove the filter line? and maybe the map line as well? I've tried distinct() but it doesn't work with field selection.

0

There are 0 answers