Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to populate with a projection in Mongoose?

Say I have a collection that contains a field that references documents from another collection like follows:

ClassEnrollment

_id | student | class
---------------------

and classes in the Class collection have the following schema:

_id | className | teacher | building | time | days | classNumber | description
------------------------------------------------------------------------------

If I have a set of 3000 classes I want to populate on the server I might do something like ClassEnrollment.populate(listOfClassEnrollments, {path: 'class'});

In my situation, I don't want the majority of the class fields though, just the name. If I get the list of 3000 classes from the db with all fields, I end up taking a performance hit in the form of network latency (these 3000 classes have to be transferred from the hosted db to the server, which might be 50 MB of raw data if the descriptions are long)

Is there a way to populate the list of class enrollments with just the name through an option to populate (behind the scenes I imagine it would work like a projection, so the db just responds with the class name and _id instead of all the class information)?

like image 654
Asksdumbquestions Avatar asked Feb 09 '15 16:02

Asksdumbquestions


1 Answers

You can use the select option in your populate call to do this:

ClassEnrollment.populate(listOfClassEnrollments, {path: 'class', select: 'className'});

To specify multiple fields, use a space-separated list:

ClassEnrollment.populate(
    listOfClassEnrollments,
    {path: 'class', select: 'className classNumber'}
);
like image 94
JohnnyHK Avatar answered Oct 03 '22 19:10

JohnnyHK